2

I have a string

txt = 'text1 & ("text2" | "text3" | "text4") & "text5" ! (text6 | text7 | text8)'

Lets say I want to parse it so I end up with elements that are between parenthesis. My pattern looks like

pattern = '\(([^\)(]+)\)'

using python I end up with two groups

>>> print re.findall(pattren, text)
['"text2" | "text3" | "text4"', 'text6 | text7 | text8']

Lets say we want to find some thing like

>>> print re.findall(magic_pattren, text )
['& ("text2" | "text3" | "text4")', '! (text6 | text7 | text8)']

Any guesses on what that magic_pattren would be. I can work my way to the desired output using string operations.

 >>> print [txt[str.find(txt, a)-3: 1+len(a)+str.find(txt, a)] for a in re.findall(pattren, txt)]
 ['& ("text2" | "text3" | "text4")', '! (text6 | text7 | text8)']

But this feels a bit clunky and fails if the parenthesis group is in the beginning. I can add a check on that, but like I said feels a bit clunky. Any takers?

4
  • Please check this demo with the r'\B\W\s*\([^()]+\)' regex. Commented Mar 8, 2016 at 8:06
  • Thanks for that, but this will miss if the group is in start. ideone.com/eWvumU Commented Mar 8, 2016 at 8:12
  • So, make that part optional, see this update Commented Mar 8, 2016 at 8:17
  • Got that.. gold thats what this is... Commented Mar 8, 2016 at 8:19

1 Answer 1

2

You can use the (?:\B\W\s*)? optional group at the beginning of the pattern:

import re
p = re.compile(r'(?:\B\W\s*)?\([^()]+\)')
test_str = "(text9 & text10) & text1 & (\"text2\" | \"text3\" | \"text4\") & \"text5\" ! (text6 | text7 | text8)"
print(p.findall(test_str))

Result of the sample demo: ['(text9 & text10)', '& ("text2" | "text3" | "text4")', '! (text6 | text7 | text8)']

The (?:\B\W\s*)? is a non-capturing group (so that the value is not output in the result) that can be repeated one or zero times (due to the last ?), and it matches a non-word character (\W) only if it is preceded with a non-word character or start of string (\B) and followed with 0+ whitespace.

Here is the regex demo

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.