0

I'm having trouble getting a regex to find the correct groups, even though the string does match. Examples of strings and desired groups:

12A TEST    # Groups: [12, A, TEST]
12 A TEST   # Groups: [12, A, TEST]
9 B         # Groups: [9, B]
8 TEST A B  # Groups: [8, TEST, A, B]

Basically a number, followed by an optional space, followed by any amount of words (separated by spaces).

The closest I've come up with is this, which matches the string, but only results in 2 groups for the first example: [12, A TEST]

/(\d+)\s*([\w+\s*]+)/g

Note: I'm using regexpal.com to test my regex. It's set to use the JS engine, but the actual regex will run in Python, if that matters at all.

Eduard Luca
  • 6,280
  • 15
  • 77
  • 133
  • The amount of groups is fixed by the number of capturing groups in the pattern. You can't have a variable amount of them. Capture all of these repetitions, then split when the match is found. Or, use captures with PyPi regex module. – Wiktor Stribiżew Apr 09 '20 at 10:55
  • FYI: `[\w+\s*]+` matches 1 or more word character or plus sign or space or asterisk, I'm pretty sure that is not what you want. – Toto Apr 09 '20 at 12:09

0 Answers0