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
afollowing by 5b.We have 2
afollowing by 2b.We have 3
afollowing by 3b.
I want to say
We have
afollowing bybwhereaandbhave 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, ...
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.
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
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