-1

I have a regex pattern to capture three group:

(([abc])([abc])([abc]))

How can I rewrite this in the other way?

I tried:

(([abc]){1,3})

But only the last group was captured.

Thanks in advance.

Hoang Hong Khang
  • 43
  • 1
  • 1
  • 6

2 Answers2

1

If I got your point, you want to capture groups of "abc" as a whole bloc. For example, abcabcabc and not abcabbc. If it's the case, then you should use (abc){1,3}. See https://regex101.com/r/kX8aB7/3

riroo
  • 134
  • 3
  • 15
0

You can't do this differently unless you use certain regex-engines (I believe .net supports it). If you repeat a capture-group, a repeated match will override the earlier found match of that capture-group. That's why you end up with only the last match.

This is of course a limitation if you don't know how many instances of a sub-pattern are gonna appear but you want to capture each individual match of the sub-pattern in a capture group.

One way around this, depending on the (programming) environment, is to match the repeated pattern as 1 bigger capture group and then run a new regex on the found capture. Example:

var inp = 'some string that matches regex & ac but we don\'t know how many letters after the regex';

var m = inp.match(/(regex).*?([abc]{1,3})/);
          
document.getElementById('out').value=m[2].match(/[abc]/g).join('\n');
<textarea id="out" rows="5" style="width:100%"></textarea>
asontu
  • 4,548
  • 1
  • 21
  • 29