Regex to check if a number is even
Can we have a regex to detect if a number is even ?
I was won开发者_如何学编程dering 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 anchor
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 lastchar
represents an even digit would be more efficient.
If it is a string, just check if endsWith
(0) || endsWith(2) || ..
returns true. If it is number, it is very simple.
Try this, I'm not sure if it's the same syntax in java:
^\d*(2|4|6|8|0)$
Sure, you just check if the last number is a 0/2/4/6/8
Never use regex for a job that can be easily done otherwise.
I came across this Microsoft blog that says the same: Link
精彩评论