Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to check if a number is even

Tags:

java

regex

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

like image 702
user441425 Avatar asked Sep 08 '10 08:09

user441425


People also ask

How do I match a specific number in regex?

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.

What is regex\\ w+?

\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.

What is\\ d in regex?

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.


3 Answers

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
like image 93
codaddict Avatar answered Sep 18 '22 10:09

codaddict


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.
like image 28
Bozho Avatar answered Sep 19 '22 10:09

Bozho


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

like image 33
fastcodejava Avatar answered Sep 20 '22 10:09

fastcodejava