Take the 2-minute tour ×

Can we have a regex to detect if a number is even ?

I was wondering if we can have a regex to do this instead of usual % or bit operations.

Thanks for replies :)

share|improve this question
Regexes operate on strings, but evenness is a property of numbers. What format are your numbers potentially in, in string format? –  AakashM Sep 8 '10 at 9:01
Please: only wonder about this, DON'T do it. Primitive integral types (byte, short, int and long) are made for storing numbers. BigInteger is made for storing really big numbers. Strings are for storing strings. –  helios Sep 8 '10 at 9:19
Interview question, anyone? –  Alex Feinman Sep 8 '10 at 13:22

6 Answers 6

up vote 21 down vote accepted

Since the correct answer has already been given, I'll argue that regex would not be my first choice for this.

  • if the number fits the long range, use %
  • if it does not, you can use BigInteger.remainder(..), but perhaps checking whether the last char represents an even digit would be more efficient.
share|improve this answer
Another trick is to check the rightmost digit is 0 or 1 which will be : (n & 1) == 1. True means odd, otherwise even –  Hendra Jaya Sep 8 '10 at 12:05

You can try:



  • ^ : Start anchor.
  • -? : Optional negative sign.
  • \d* : Zero or more digits.
  • [02468] : Char class to match a 0 or 2 or 4 or 6 or 8
  • $ : End anchor
share|improve this answer
fastest and with explanation. kudos. –  Stephan Muller Sep 8 '10 at 9:00
Nice that you did not forget the negative values.;) –  Caspar Kleijne Sep 8 '10 at 14:51

Sure, you just check if the last number is a 0/2/4/6/8

share|improve this answer

Try this, I'm not sure if it's the same syntax in java:

share|improve this answer

If it is a string, just check if endsWith(0) || endsWith(2) || .. returns true. If it is number, it is very simple.

share|improve this answer

Never use regex for a job that can be easily done otherwise.

I came across this Microsoft blog that says the same: http://blogs.msdn.com/b/bclteam/archive/2005/02/21/377575.aspx

share|improve this answer
Can you elaborate what is in the link or why not use a regex in this instance? –  Jon Lin Dec 8 '12 at 21:39

Your Answer


