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?
Chaining regular expressionsRegular expressions can be chained together using the pipe character (|). This allows for multiple search options to be acceptable in a single regex string.
Multiline option, or the m inline option, enables the regular expression engine to handle an input string that consists of multiple lines. It changes the interpretation of the ^ and $ language elements so that they match the beginning and end of a line, instead of the beginning and end of the input string.
What is Group in Regex? A group is a part of a regex pattern enclosed in parentheses () metacharacter. We create a group by placing the regex pattern inside the set of parentheses ( and ) . For example, the regular expression (cat) creates a single group containing the letters 'c', 'a', and 't'.
A Match is an object that indicates a particular regular expression matched (a portion of) the target text. A Group indicates a portion of a match, if the original regular expression contained group markers (basically a pattern in parentheses).
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:
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
.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With