Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

regex

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?

like image 986
Dave Johnson Avatar asked Aug 10 '15 01:08

Dave Johnson


People also ask

Can you chain regex?

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.

What is multiline matching?

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.

How does regex grouping work?

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'.

What is the difference between a match and group in regex?

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).


1 Answers

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.
like image 139
alpha bravo Avatar answered Oct 24 '22 23:10

alpha bravo