473,386 Members | 1,773 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

splitting words with brackets

I've got some strings to split. They are main words, but some words
are inside a pair of brackets and should be considered as one unit. I
prefer to use re.split, but haven't written a working one after hours
of work.

Example:

"a (b c) d [e f g] h i"
should be splitted to
["a", "(b c)", "d", "[e f g]", "h", "i"]

As speed is a factor to consider, it's best if there is a single line
regular expression can handle this. I tried this but failed:
re.split(r"(?![\(\[].*?)\s+(?!.*?[\)\]])", s). It work for "(a b) c"
but not work "a (b c)" :(

Any hint?

Jul 26 '06 #1
17 8176
re.findall('\([^\)]*\)|\[[^\]]*|\S+', s)

Qiangning Hong wrote:
I've got some strings to split. They are main words, but some words
are inside a pair of brackets and should be considered as one unit. I
prefer to use re.split, but haven't written a working one after hours
of work.

Example:

"a (b c) d [e f g] h i"
should be splitted to
["a", "(b c)", "d", "[e f g]", "h", "i"]

As speed is a factor to consider, it's best if there is a single line
regular expression can handle this. I tried this but failed:
re.split(r"(?![\(\[].*?)\s+(?!.*?[\)\]])", s). It work for "(a b) c"
but not work "a (b c)" :(

Any hint?
Jul 26 '06 #2
er,
....|\[[^\]]*\]|...
^_^

faulkner wrote:
re.findall('\([^\)]*\)|\[[^\]]*|\S+', s)

Qiangning Hong wrote:
I've got some strings to split. They are main words, but some words
are inside a pair of brackets and should be considered as one unit. I
prefer to use re.split, but haven't written a working one after hours
of work.

Example:

"a (b c) d [e f g] h i"
should be splitted to
["a", "(b c)", "d", "[e f g]", "h", "i"]

As speed is a factor to consider, it's best if there is a single line
regular expression can handle this. I tried this but failed:
re.split(r"(?![\(\[].*?)\s+(?!.*?[\)\]])", s). It work for "(a b) c"
but not work "a (b c)" :(

Any hint?
Jul 26 '06 #3
faulkner wrote:
re.findall('\([^\)]*\)|\[[^\]]*|\S+', s)
sorry i forgot to give a limitation: if a letter is next to a bracket,
they should be considered as one word. i.e.:
"a(b c) d" becomes ["a(b c)", "d"]
because there is no blank between "a" and "(".

Jul 26 '06 #4
faulkner wrote:
er,
...|\[[^\]]*\]|...
^_^
That's why it is nice to use re.VERBOSE:

def splitup(s):
return re.findall('''
\( [^\)]* \) |
\[ [^\]]* \] |
\S+
''', s, re.VERBOSE)

Much less error prone this way

--
- Justin

Jul 26 '06 #5
"a (b c) d [e f g] h i"
should be splitted to
["a", "(b c)", "d", "[e f g]", "h", "i"]

As speed is a factor to consider, it's best if there is a
single line regular expression can handle this. I tried
this but failed:
re.split(r"(?![\(\[].*?)\s+(?!.*?[\)\]])", s). It work
for "(a b) c" but not work "a (b c)" :(

Any hint?
[and later added]
sorry i forgot to give a limitation: if a letter is next
to a bracket, they should be considered as one word. i.e.:
"a(b c) d" becomes ["a(b c)", "d"] because there is no
blank between "a" and "(".
>>import re
s ='a (b c) d [e f g] h ia abcd(b c)xyz d [e f g] h i'
r = re.compile(r'(?:\S*(?:\([^\)]*\)|\[[^\]]*\])\S*)|\S+')
r.findall(s)
['a', '(b c)', 'd', '[e f g]', 'h', 'ia', 'abcd(b c)xyz', 'd',
'[e f g]', 'h', 'i']

I'm sure there's a *much* more elegant pyparsing solution to
this, but I don't have the pyparsing module on this machine.
It's much better/clearer and will be far more readable when
you come back to it later.

However, the above monstrosity passes the tests I threw at
it.

-tkc


Jul 26 '06 #6
Qiangning Hong wrote:
faulkner wrote:
re.findall('\([^\)]*\)|\[[^\]]*|\S+', s)

sorry i forgot to give a limitation: if a letter is next to a bracket,
they should be considered as one word. i.e.:
"a(b c) d" becomes ["a(b c)", "d"]
because there is no blank between "a" and "(".
This variation seems to do it:

import re

s = "a (b c) d [e f g] h i(j k) l [m n o]p q"

def splitup(s):
return re.findall('''
\S*\( [^\)]* \)\S* |
\S*\[ [^\]]* \]\S* |
\S+
''', s, re.VERBOSE)

print splitup(s)

# Prints

['a', '(b c)', 'd', '[e f g]', 'h', 'i(j k)', 'l', '[m n o]p', 'q']
Peace,
~Simon

Jul 26 '06 #7
Tim Chase wrote:
>>import re
>>s ='a (b c) d [e f g] h ia abcd(b c)xyz d [e f g] h i'
>>r = re.compile(r'(?:\S*(?:\([^\)]*\)|\[[^\]]*\])\S*)|\S+')
>>r.findall(s)
['a', '(b c)', 'd', '[e f g]', 'h', 'ia', 'abcd(b c)xyz', 'd',
'[e f g]', 'h', 'i']
[...]
However, the above monstrosity passes the tests I threw at
it.
but it can't pass this one: "(a c)b(c d) e"
the above regex gives out ['(a c)b(c', 'd)', 'e'], but the correct one
should be ['(a c)b(c d)', 'e']

Jul 26 '06 #8
Simon Forman wrote:
def splitup(s):
return re.findall('''
\S*\( [^\)]* \)\S* |
\S*\[ [^\]]* \]\S* |
\S+
''', s, re.VERBOSE)
Yours is the same as Tim's, it can't handle a word with two or more
brackets pairs, too.

I tried to change the "\S*\([^\)]*\)\S*" part to "(\S|\([^\)]*\))*",
but it turns out to a mess.

Jul 26 '06 #9
but it can't pass this one: "(a c)b(c d) e" the above regex
gives out ['(a c)b(c', 'd)', 'e'], but the correct one should
be ['(a c)b(c d)', 'e']
Ah...the picture is becoming a little more clear:
>>r = re.compile(r'(?:\([^\)]*\)|\[[^\]]*\]|\S)+')
r.findall(s)
['(a c)b(c d)', 'e']

It also works on my original test data, and is a cleaner regexp
than the original.

The clearer the problem, the clearer the answer. :)

-tkc


Jul 26 '06 #10

Qiangning Hong wrote:
Tim Chase wrote:
>>import re
>>s ='a (b c) d [e f g] h ia abcd(b c)xyz d [e f g] h i'
>>r = re.compile(r'(?:\S*(?:\([^\)]*\)|\[[^\]]*\])\S*)|\S+')
>>r.findall(s)
['a', '(b c)', 'd', '[e f g]', 'h', 'ia', 'abcd(b c)xyz', 'd',
'[e f g]', 'h', 'i']
[...]
However, the above monstrosity passes the tests I threw at
it.

but it can't pass this one: "(a c)b(c d) e"
the above regex gives out ['(a c)b(c', 'd)', 'e'], but the correct one
should be ['(a c)b(c d)', 'e']
What are the desired results in cases like this:

"(a b)[c d]" or "(a b)(c d)" ?

Jul 26 '06 #11
Simon Forman wrote:
What are the desired results in cases like this:

"(a b)[c d]" or "(a b)(c d)" ?
["(a b)[c d]"], ["(a b)(c d)"]

Jul 26 '06 #12
Tim Chase wrote:
Ah...the picture is becoming a little more clear:
>>r = re.compile(r'(?:\([^\)]*\)|\[[^\]]*\]|\S)+')
>>r.findall(s)
['(a c)b(c d)', 'e']

It also works on my original test data, and is a cleaner regexp
than the original.

The clearer the problem, the clearer the answer. :)
Ah, it's exactly what I want! I thought the left and right sides of
"|" are equal, but it is not true. I think I must sleep right now,
lacking of sleep makes me a dull :-p. Thank you and Simon for your
kindly help!

Jul 26 '06 #13
"Tim Chase" <py*********@tim.thechases.comwrote in message
news:ma***************************************@pyt hon.org...
I'm sure there's a *much* more elegant pyparsing solution to
this, but I don't have the pyparsing module on this machine.
It's much better/clearer and will be far more readable when
you come back to it later.

However, the above monstrosity passes the tests I threw at
it.

-tkc
:) Cute! (but how come no pyparsing on your machine?)

Ok, I confess I looked at the pyparsing list parser to see how it compares.
Pyparsing's examples include a list parser that comprehends nested lists
within lists, but this is a bit different, and really more straightforward.

Here's my test program for this modified case:

wrd = Word(alphas)
parenList = Combine( Optional(wrd) + "(" + SkipTo(")") + ")" +
Optional(wrd) )
brackList = Combine( Optional(wrd) + "[" + SkipTo("]") + "]" +
Optional(wrd) )
listExpr = ZeroOrMore( parenList | brackList | wrd )

txt = "a (b c) d [e f g] h i(j k) l [m n o]p q"
print listExpr.parseString(txt)

Gives:
['a', '(b c)', 'd', '[e f g]', 'h', 'i(j k)', 'l', '[m n o]p', 'q']
Comparitive timing of pyparsing vs. re comes in at about 2ms for pyparsing,
vs. 0.13 for re's, so about 15x faster for re's. If psyco is used (and we
skip the first call, which incurs all the compiling overhead), the speed
difference drops to about 7-10x. I did try compiling the re, but this
didn't appear to make any difference - probably user error.

Since the OP indicates a concern for speed (he must be compiling a lot of
strings, I guess), it would be tough to recommend pyparsing - especially in
the face of a working re that so neatly does the trick. But if at some
point it became necessary to add support for {}'s and <>'s, or quoted
strings, I'd rather be working with a pyparsing grammar than that crazy re
gibberish!

-- Paul

Jul 26 '06 #14
Ah, I had just made the same change!
from pyparsing import *

wrd = Word(alphas)
parenList = "(" + SkipTo(")") + ")"
brackList = "[" + SkipTo("]") + "]"
listExpr = ZeroOrMore( Combine( OneOrMore( parenList | brackList | wrd ) ) )

t = "a (b c) d [e f g] h i(j k) l [m n o]p q r[s] (t u)v(w) (x)(y)z"
print listExpr.parseString(t)
Gives:
['a', '(b c)', 'd', '[e f g]', 'h', 'i(j k)', 'l', '[m n o]p', 'q', 'r[s]',
'(t u)v(w)', '(x)(y)z']

Jul 26 '06 #15
>>r = re.compile(r'(?:\([^\)]*\)|\[[^\]]*\]|\S)+')
>>r.findall(s)
['(a c)b(c d)', 'e']

Ah, it's exactly what I want! I thought the left and right
sides of "|" are equal, but it is not true.
In theory, they *should* be equal. I was baffled by the nonparity
of the situation. You *should" be able to swap the two sides of
the "|" and have it treated the same. Yet, when I tried it with
the above regexp, putting the \S first, it seemed to choke and
give different results. I'd love to know why.
Thank you and Simon for your kindly help!
My pleasure. A nice diversion from swatting spammers and getting
our network back up and running today. I had hoped to actually
get something productive done (i.e. writing some python code)
rather than putting out fires. Sigh.

-tkc


Jul 27 '06 #16
Paul McGuire wrote:
Comparitive timing of pyparsing vs. re comes in at about 2ms for pyparsing,
vs. 0.13 for re's, so about 15x faster for re's. If psyco is used (and we
skip the first call, which incurs all the compiling overhead), the speed
difference drops to about 7-10x. I did try compiling the re, but this
didn't appear to make any difference - probably user error.
That is because of how the methods in the sre module are implemented...
Compiling a regex really just saves you a dictionary lookup.

def findall(pattern, string, flags=0):
"""snip"""
return _compile(pattern, flags).findall(string)

def compile(pattern, flags=0):
"""snip"""
return _compile(pattern, flags)

def _compile(*key):
# internal: compile pattern
cachekey = (type(key[0]),) + key
p = _cache.get(cachekey)
if p is not None:
return p
#snip

--
- Justin

Jul 27 '06 #17

"Tim Chase" <py*********@tim.thechases.comwrote in message
news:ma***************************************@pyt hon.org...
>r = re.compile(r'(?:\([^\)]*\)|\[[^\]]*\]|\S)+')
r.findall(s)
['(a c)b(c d)', 'e']
Ah, it's exactly what I want! I thought the left and right
sides of "|" are equal, but it is not true.

In theory, they *should* be equal. I was baffled by the nonparity
of the situation. You *should" be able to swap the two sides of
the "|" and have it treated the same. Yet, when I tried it with
the above regexp, putting the \S first, it seemed to choke and
give different results. I'd love to know why.
Does the re do left-to-right matching? If so, then the \S will eat the
opening parens/brackets, and never get into the other alternative patterns.
\S is the most "matchable" pattern, so if it comes ahead of the other
alternatives, then it will always be the one matched. My guess is that if
you put \S first, you will only get the contiguous character groups,
regardless of ()'s and []'s. The expression might as well just be \S+.

Or I could be completely wrong...

-- Paul
Jul 27 '06 #18

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: Piotr | last post by:
Is there any way to split all merged words but www and e-mail addresses? I have regexp preg_replace("/(\.)(])/", "\\1 \\2", "www.google.com any,merged.words mymail@domain.com") it give me...
16
by: audleman | last post by:
I'm attempting to build a query that involves a table called "All Students". The query is simply sqlString = "SELECT * FROM All Students" but I get "Syntax error in FROM clause" when I try...
7
by: Anat | last post by:
Hi, What regex do I need to split a string, using javascript's split method, into words-array? Splitting accroding to whitespaces only is not enough, I need to split according to whitespace,...
2
by: Anat | last post by:
Hi, I need a little help on performing string manipulation: I want to take a given string, and make certain words hyperlinks. For example: "Hello world, this is a wonderful day!" I'd like the...
12
by: Simon | last post by:
Well, the title's pretty descriptive; how would I be able to take a line of input like this: getline(cin,mostrecentline); And split into an (flexible) array of strings. For example: "do this...
9
by: conspireagainst | last post by:
I'm having quite a time with this particular problem: I have users that enter tag words as form input, let's say for a photo or a topic of discussion. They are allowed to delimit tags with spaces...
2
by: shadow_ | last post by:
Hi i m new at C and trying to write a parser and a string class. Basicly program will read data from file and splits it into lines then lines to words. i used strtok function for splitting data to...
4
by: techusky | last post by:
I am making a website for a newspaper, and I am having difficulty figuring out how to take a string (the body of an article) and break it up into three new strings so that I can display them in the...
5
by: Ciaran | last post by:
Hi Can someone please give me a hand adapting this expression? I need it to add a space into all words longer than 14 characters that are not contained within $result =...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.