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]'?

KevinZhou
  • 447
  • 4
  • 10
  • There is no nested anything in your string. –  Apr 28 '19 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. –  Apr 28 '19 at 17:45
  • 1
    @sln Thanks!!! I knew what my problem is! – KevinZhou Apr 28 '19 at 20:14

0 Answers0