Dave Johnson
Dave Johnson

Reputation: 381

Can I make two groups of regex match in same quantity?

I want a regex that matches the following pattern:

b
abc
aabcc
aaabccc

But does NOT match any of:

ab
bc
aabc
abcc

Basically, /(a)*b(c){_Q_}/, where _Q_ is the number of times that group 1 matched. I know how to match group 1 content later in the string, but how can I match group 1 count?

Upvotes: 6

Views: 761

Answers (1)

alpha bravo
alpha bravo

Reputation: 7948

Use this recursive regex:

^(a(?:(?1)|b)c)$|^(b)$

Demo on regex101

The regex can be further reduced to:

^(a(?1)c|b)$

Demo on regex101

The alternation consists of:

  • The base case b
  • The recursive case a(?1)c which matches a, then recurse into group 1, then matches c. Group 1 is the alternation itself, so it can contain more pairs of a and c, or the recursion ends at base case b.

Upvotes: 7

Related Questions