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 :)
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 :)
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 anchorTry this, I'm not sure if it's the same syntax in java:
^\d*(2|4|6|8|0)$
If it is a string, just check if endsWith
(0) || endsWith(2) || ..
returns true. If it is number, it is very simple.
Since the correct answer has already been given, I'll argue that regex would not be my first choice for this.
long
range, use %
BigInteger.remainder(..)
, but perhaps checking whether the last char
represents an even digit would be more efficient.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