view raw
Raj Raj - 5 months ago 42
Python Question

extracting string using capture groups (using re.match)

Here is my regular expression where I am trying to retrive 3 Capture groups

res = re.match("^(?![()]*)([()])(.*)$", input)

and this is my expected result

input = "This is a ()demo)"
I would need 3 capture groups -> "This is a " -> "(" -> ")demo)"

input = "Another demo )(continues...()" -> "Another demo " -> ")" -> "(continues...()"

input = "(last demo () and finally" -> "" -> "(" -> "last demo () and finally"

But the regex I have written do not match any of the 3 inputs I have given above. What am I doing wrong here?


The first thing you're doing wrong is using a negative lookahead assertion


I'm guessing you were trying to say "match any character except ()". You can do that with the regular matching groups by starting the group with a ^ symbol.


Otherwise, your regex is pretty much correct.

Here is a regex that will give you the expected output