tags:

views:

469

answers:

6

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

+47  A: 

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
codaddict
fastest and with explanation. kudos.
Litso
Nice that you did not forget the negative values.;)
Caspar Kleijne
+1  A: 

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

Litso
+1  A: 

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

^\d*(2|4|6|8|0)$
aularon
+4  A: 

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

fastcodejava
+15  A: 

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.
Bozho
jancrot
A: 

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

Jone