I have a regex question that I do not know how to do. It has to match all strings consisting any number of a's at the beginning and then either a single 0 if the number of a's was even or a single 1 if the number of a's was odd.
How can you keep track of even/odd?
Sample
^(a(aa)*1|(aa)+0)$
or
^(?:a(?:aa)*1|(?:aa)+0)$
if you are using captures.
The first portion: a(aa)*1
will match any odd number of a's followed by a one, and the second portion: (aa)+0
will match any even number of a's followed by a zero.
You can't keep track of the number of matches of a component of the pattern in regular expressions. They don't have memory. Fortunately, you can get around that limitation in this case.
You could use:
^(?:aa)*(?:a1|0)$
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