Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there a regular expression that can recognize positive even numbers (including numbers with leading zeros, but excluding "0000" numbers)?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading