Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reuse the number of group matches with regex?

I'm using this regex ^x{3}y{3}$ to check for example this string: xxxyyy, where the number of x's is the same as the number of y's (in my example it is 3). But the problem is that I don't know the number of repetitions (it is in range from 0 to 10), so 3 has to be replaced with something abstract.

I can use ^x*y*$ or ^x{0,10}y{0,10}$, but this will not work when the number of x's is different from the number of y's.

I'm looking for something like \1, which is used for reusing of matched group, but in my case I want to reuse the number of group matches for x.

like image 640
Termininja Avatar asked Aug 28 '16 09:08

Termininja


People also ask

What does ++ mean in regex?

++ From What is double plus in regular expressions? That's a Possessive Quantifier. It basically means that if the regex engine fails matching later, it will not go back and try to undo the matches it made here.

How do I match a range of numbers in regex?

With regex you have a couple of options to match a digit. You can use a number from 0 to 9 to match a single choice. Or you can match a range of digits with a character group e.g. [4-9]. If the character group allows any digit (i.e. [0-9]), it can be replaced with a shorthand (\d).

What does (? I do in regex?

(? i) makes the regex case insensitive. (? c) makes the regex case sensitive.


1 Answers

Since you've got a fixed upper limit, you could just list the matches out longhand:

^(x{10}y{10}|x{9}y{9}|x{8}y{8}|x{7}y{7}|x{6}y{6}|x{5}y{5}|x{4}y{4}|x{3}y{3}|x{2}y{2}|xy)?$

(The ? handles your "zero of each" case.)

Clearly if x and y are long in practice then there will be lots of repetition here.

Another approach would be to repeatedly replace xy with an empty string, and check that you end up with an empty string (since each time you remove a pair, you'll bring another pair together).

like image 127
Matthew Strawbridge Avatar answered Sep 25 '22 16:09

Matthew Strawbridge