Can I make two groups of regular expressions in one quantity?

I want the regular expression to match 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 matches in group 1. I know how to associate group 1 contents later on the line, but how can I match group 1 count ?

+6
source share
1 answer

Use this recursive regular expression:

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

Demo on regex101

The regular expression can be further reduced to:

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

Demo on regex101

The shift consists of:

  • Base case b
  • The recursive case a(?1)c , which corresponds to a , is then rewritten to group 1, then corresponds to c . Group 1 is the sequence itself, so it can contain more pairs a and c , or the recursion ends in the base case b .
+6
source

All Articles