fronthem
fronthem

Reputation: 4139

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

Upvotes: 4

Views: 104

Answers (3)

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89584

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

Upvotes: 4

Eder
Eder

Reputation: 1884

Assuming that you want to evenly match the same number of a & b, you can use recursion with in your regular expression,

Eg: /a(?R)?b/

Above pattern will match:

  • ab
  • aabb
  • aaabbb
  • aaaabbbb

Please note that not all the regex engines support recursion, but if you are using a PCRE based engined you will be able.

Upvotes: 2

Felix Kling
Felix Kling

Reputation: 816910

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.

Upvotes: 6

Related Questions