0

How to match multiple times a group using a simple regex. I try with this: (?:key:)((?:\s*'[^']+')), but does not work.

Input

key: 'val1' 'val2' 'val3'

Output

group 1 = val1

group 2 = val2

group 3 = val3

EDIT: How to find all tags enclosed by simples quotes after a desired key?

Luis Daniel
  • 687
  • 7
  • 18

2 Answers2

0

You can't directly do what you want. With regex you can't have a variable number of capturing groups.

However. If your amount of groups is limited, then you could repeat (?:\s*('[^']+')*)? for that limit. Thus to be able to match your given example, you'd need.

key:(?:\s*('[^']+')*)?(?:\s*('[^']+')*)?(?:\s*('[^']+')*)?

Note that (?:\s*('[^']+')*)? has been repeated 3 times.

Live preview

It might be easier and better to just iterate over this pattern '[^']+'. As you didn't mention any language, I took the liberty of doing it in Python.

import re
string = "'val1' 'val2' 'val3'"
for i, match in enumerate(re.finditer(r"'([^']+)'", string), start=1):
    print("group %d = %s" % (i, match.group(1)))

The above when executed will print:

group 1 = val1

group 2 = val2

group 3 = val3

So instead of trying to make a "variable" number of capturing groups. Instead try an iterate all the matches for the quotes pattern.

Community
  • 1
  • 1
vallentin
  • 23,478
  • 6
  • 59
  • 81
0

I solved this problem using the following regular expression: (?:key:\G)|('[^']+')+, here is the link to check how it works.

Luis Daniel
  • 687
  • 7
  • 18