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
.
++ 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.
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).
(? i) makes the regex case insensitive. (? c) makes the regex case sensitive.
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).
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