Reputation: 4139
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 5b
.We have 2
a
following by 2b
.We have 3
a
following by 3b
.
I want to say
We have
a
following byb
wherea
andb
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
Reputation: 89584
You can achieve this too without recursion:
(?:a(?=[^b]*(\1?+b)))+\1
or with a conditional test:
(?:a(?=[^b]*((?(1)\1b|b))))+\1
Upvotes: 4
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:
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
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