0

I have a regex which has nested group in it, the returned result does match my expectation, can anyone tell me why?

input_string = "(;A[B][D];B[C])"
regex_str = r'\(;([A-Z]+(\[\w+\])+)*(.*)\)'
result = re.findall(regex_str, input_string)

I expected the output to be:

[('A[B][D]', '[B][D]', ';B[C]')]

However, the actual output is:

[('A[B][D]', '[D]', ';B[C]')]

Why didn't (\[\w+\])+ match '[B][D]' instead of '[D]'?

3
  • There is no nested anything in your string. Commented Apr 28, 2019 at 17:41
  • 2
    ( \[ \w+ \] )+ did match [B][D] just one at a time. The last thing a group matches is retained with the group. In this case [D] is the last thing group 2 matched. Commented Apr 28, 2019 at 17:45
  • 1
    @sln Thanks!!! I knew what my problem is! Commented Apr 28, 2019 at 20:14

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.