Raj Raj - 2 months ago 27
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
res.group(1) -> "This is a "
res.group(2) -> "("
res.group(3) -> ")demo)"

input = "Another demo )(continues...()"
res.group(1) -> "Another demo "
res.group(2) -> ")"
res.group(3) -> "(continues...()"

input = "(last demo () and finally"
res.group(1) -> ""
res.group(2) -> "("
res.group(3) -> "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