I am trying to capture a variable number of groups on a string using a python regex like the following:

matchre = re.search(r"^Hello\sThere\s(?P<first>[ 0-9\.]+?)\s(?:\[(?P<sqbracks>.+?)\]\s)+here\s(?P<second>\S+)\sare.*$", "Hello There 1.0.0 [AAA] [BBB] [CCC] here we are")
version = matchre.group('first')
second = matchre.group('second')
sqbracks = matchre.group('sqbracks')

The code above has the following results on Python 2.7.13:


I have the following problems with this:

  1. I always get the last square bracket group, in this case "CCC", and not each of three of them, i.e. AAA BBB CCC.
  2. I have no way to capture all the square bracket groups if they vary in number, i.e. I cannot capture the square bracket contents from the following strings using the same regex:
 Hello There 1.0.0 [AAA] here we are
 Hello There 2.0.0 [AAA] [BBB] here we are
 Hello There 3.0.0 [AAA] [BBB] [CCC] here we are

Are there any ideas on this?

0 Answers