parse a string using regex
Question: 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?


Answer: 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](https://ideone.com/0kR8rV): `['(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](https://regex101.com/r/gO2iU7/3)

