Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saying that two letters have the same quantifier without specifying a number in Regex

Tags:

regex

Example

string1 = aaaaabbbbb
regex1 = a{5}b{5}

string2 = aabb
regex2 = a{2}b{2}

string2 = aaabbb
regex2 = a{3}b{3}

You will see that the 3 examples above I need to specify quantifiers of them.

Instead of saying

We have 5 a following by 5 b.

We have 2 a following by 2 b.

We have 3 a following by 3 b.

I want to say

We have a following by b where a and b have the same quantifier.

It is possible or not that I will use only one regex to catch all these patterns, the Regex might similar to this

a{n}b{n}

where n stands for any number.

Note that the best answer should also be able to solve aaaxyzbbb, aaaaxyzbbbb, ...

like image 565
fronthem Avatar asked Dec 15 '22 12:12

fronthem


2 Answers

This can be achieved with recursion. For example:

 a(?R)?b

However, the exact syntax and whether it is supported in the first place depends on the regex flavor you are using.

See this article for more information.

like image 165
Felix Kling Avatar answered Apr 25 '23 15:04

Felix Kling


You can achieve this too without recursion:

(?:a(?=[^b]*(\1?+b)))+\1

demo

or with a conditional test:

(?:a(?=[^b]*((?(1)\1b|b))))+\1

demo

like image 41
Casimir et Hippolyte Avatar answered Apr 25 '23 16:04

Casimir et Hippolyte