Home > Back-end >  Is there a regular expression that can recognize positive even numbers (including numbers with leadi
Is there a regular expression that can recognize positive even numbers (including numbers with leadi

Time:11-14

Like I said in the title, I am having a hard time writing this particular regular expression. Any help would be much appreciated.

My best attempt in trying to solve this problem was writing this:

^([0-9]*[1-9][0-9]*)*[02468]$

But this regular expression can't recognize a number like "002". Then I have tried this:

^([0-9]*[1-9][0-9]*)*[02468]*[02468]$

Now regular expression recognizes "002", but also recognizes "000" (only zeros) and I can't avoid that happening.

In conclusion, I am failing again and again in writing a regular expression that can recognize positive even numbers (including leading zeros, but excluding "000" - numbers with only zeros) like:

2, 001234, 00123400, 002, 20, 16 etc.

Thank you in advance.

CodePudding user response:

You could use a positive lookahead for any digit except 0:

^(?=.*[1-9])[0-9]*[02468]$
  • (?=.*[1-9]) - positive lookahead for any digit except 0
  • [0-9]* - any digit repeated 0 or more times
  • [02468] - any even digit

Demo

CodePudding user response:

You could match at least a single digit not being zero, or match at least 2 digits where the first one is 1-9

^(?:[0-9]*[2468]|0*[1-9][0-9]*[02468])$

Explanation

  • ^ Start of string
  • (?: Non capture group
    • [0-9]*[2468] Match optional digits 0-9 and then one of 2 4 6 8
    • | Or
    • 0*[1-9][0-9]*[02468] Match optional zeroes, a digit 1-9 optional digits 0-9 and then one of 2 4 6 8
  • ) Close the non capture group
  • $ End of string

Regex demo

Or you could assert not only zeroes in the string using a negative lookahead (?!0 $)

^(?!0 $)[0-9]*[02468]$

Regex demo

  • Related