Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex Odd/Even Amount

Tags:

java

regex

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

  • aaa1
  • aaaa0
like image 259
Mat.S Avatar asked Aug 04 '13 07:08

Mat.S


2 Answers

^(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.

like image 96
Chris Bode Avatar answered Nov 07 '22 05:11

Chris Bode


You could use:

^(?:aa)*(?:a1|0)$
like image 21
Qtax Avatar answered Nov 07 '22 07:11

Qtax