Regex Odd / Even Amount

I have a regex question that I don't know how to do. It must correspond to all lines consisting of any number a at the beginning, and then either one at a time 0 if the number a is equal to or one if the number a was odd.

How can you track even / odd?

Example

  • AAA1
  • aaaa0
+6
source share
2 answers

^(a(aa)*1|(aa)+0)$

or

^(?:a(?:aa)*1|(?:aa)+0)$ if you use captures.

The first part: a(aa)*1 will correspond to any odd number a followed by one, and the second part: (aa)+0 will correspond to any even number a followed by zero.

You cannot track the number of matches of a template component in regular expressions. They have no memory. Fortunately, you can get around this limitation in this case.

+10
source

You can use:

 ^(?:aa)*(?:a1|0)$ 
+7
source

Source: https://habr.com/ru/post/950982/


All Articles