Reputation: 381
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
Reputation: 7948
Use this recursive regex:
^(a(?:(?1)|b)c)$|^(b)$
The regex can be further reduced to:
^(a(?1)c|b)$
The alternation consists of:
b
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