Saying that two letters have the same quantifier without specifying a number in 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 in the above examples I need to specify their quantifiers.

Instead of talking

We have 5 a, following 5 b.

We have 2 afollowing 2 b.

We have 3 a, following 3 b.

I want to say

We have a, following b, where athey bhave the same quantifier.

It is possible or not that I will use only one regular expression to catch all these patterns, Regex may be similar to this

a{n}b{n}

where ndenotes any number.

Please note that the best response must also decide aaaxyzbbb, aaaaxyzbbbb...

+4
3

:

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

:

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

+4

. :

 a(?R)?b

.

. .

+5

, a b, ,

: /a(?R)?b/

:

  • aaabbb
  • aaaabbbb

Note that not all regex engines support recursion , but if you use a PCRE based engine, you can.

+2
source

All Articles