473,750 Members | 2,190 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 #1
17 8206
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

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 #10

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

Similar topics

2
2430
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
12325
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
25789
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
2215
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
4456
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
8885
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
3269
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
2540
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
3924
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
8999
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
9394
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9338
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
9256
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...
1
6803
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
4885
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3322
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2798
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2223
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.