9

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 :)

2
  • 3
    Regexes operate on strings, but evenness is a property of numbers. What format are your numbers potentially in, in string format?
    – AakashM
    Sep 8, 2010 at 9:01
  • 13
    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, 2010 at 9:19

6 Answers 6

57

You can try:

^-?\d*[02468]$

Explanation:

  • ^ : 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
2
  • 1
    fastest and with explanation. kudos. Sep 8, 2010 at 9:00
  • 4
    Nice that you did not forget the negative values.;) Sep 8, 2010 at 14:51
22

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.
1
  • 6
    Another trick is to check the rightmost digit is 0 or 1 which will be : (n & 1) == 1. True means odd, otherwise even Sep 8, 2010 at 12:05
3

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

1

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

^\d*(2|4|6|8|0)$
1

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

0

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

I came across this Microsoft blog that says the same: Link

1
  • Can you elaborate what is in the link or why not use a regex in this instance?
    – Jon Lin
    Dec 8, 2012 at 21:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.