Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to split a string with parentheses and spaces into a list

I want to split strings like:

(so) what (are you trying to say)
 
what (do you mean)

Into lists like:

[(so), what, (are you trying to say)]

[what, (do you mean)]

The code that I tried is below. In the site regexr, the regex expression match the parts that I want but gives a warning, so… I’m not a expert in regex, I don’t know what I’m doing wrong.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import re
string = "(so) what (are you trying to say)?"

rx = re.compile(r"((\([\w \w]*\)|[\w]*))")

print(re.split(rx, string ))

>Solution :

Using [\w \w]* is the same as [\w ]* and also matches an empty string.

Instead of using split, you can use re.findall without any capture groups and write the pattern like:

\(\w+(?:[^\S\n]+\w+)*\)|\w+
  • \( Match (
    • \w+ Match 1+ word chars
    • (?:[^\S\n]+\w+)* Optionally repeat matching spaces and 1+ word chars
  • \) Match )
  • | Or
  • \w+ Match 1+ word chars

Regex demo

import re
string = "(so) what (are you trying to say)? what (do you mean)"

rx = re.compile(r"\(\w+(?:[^\S\n]+\w+)*\)|\w+")

print(re.findall(rx, string))

Output

['(so)', 'what', '(are you trying to say)', 'what', '(do you mean)']
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading