473,903 Members | 3,244 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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
17 8228
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 #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*********@ti m.thechases.com wrote in message
news:ma******** *************** *************** *@python.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.parseS tring(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.parseS tring(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(patter n, flags).findall( string)

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

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

--
- Justin

Jul 27 '06 #17

"Tim Chase" <py*********@ti m.thechases.com wrote in message
news:ma******** *************** *************** *@python.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
2440
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 incorrect result: www. google. com any, merged. words mymail@domain. com
16
12362
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 to run it. I assume this is because my table is two words. How do I get Access to recognize it?
7
25797
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, comma, hyphen, etc... Is there a regex that does the trick? Thanks, Anat.
2
2223
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 words world & and day to be hyperlinks, therefore after my manipulation it should be: "Hello <a href=...>world</a>, this is a wonderful <a href=...>day</a>!" Using split method is not good, because splitting with regex each punctuation mark causes...
12
4471
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 action" would go to: item 0: do
9
8908
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 and commas, and can use quotes to encapsulate multiple words. An example: tag1, tag2 tag3, "tag4 tag4, tag4" tag5, "tag6 tag6" So, as we can see here anything is allowed, but the problem is that splitting on commas obviously destroys tag4...
2
3283
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 lines it worked quite well but srttok isnot working for multiple blank or commas. Can strtok do this kind of splitting if it cant what should i use . Unal
4
2549
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 traditional newspaper column format. For instance, say the string $articleBody contains a 600 word article. What I want to do is break $articleBody up into three new strings in a format such as this: $string1 contains words 0-200 from...
5
3931
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 = preg_replace("/({14})/","$1 ",$result); It currently adds a space into all words that are longer than 14 characters but this is breaking another function I'm using which extracts urls and other info from inside square brackets.
0
9999
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9847
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
10983
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10500
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9684
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
8048
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
7206
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
6088
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
4308
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.