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 :)
How do I match a specific number in regex? To match any number from 0 to 9 we use \d in regex. It will match any single digit number from 0 to 9. \d means [0-9] or match any number from 0 to 9.
\w+ matches 1 or more word characters (same as [a-zA-Z0-9_]+ ). [. -]? matches an optional character . or - . Although dot ( . ) has special meaning in regex, in a character class (square brackets) any characters except ^ , - , ] or \ is a literal, and do not require escape sequence.
private final String REGEX = "\\d"; // a single digit. In this example \d is the regular expression; the extra backslash is required for the code to compile.
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 anchorSince 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.If it is a string, just check if endsWith
(0) || endsWith(2) || ..
returns true. If it is number, it is very simple.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With