For a number to be even it must end with an even digit. Even digits are 0, 2, 4, 6, and 8. Use a character class to specify which digits are allowed at each position.
The answer is:
/^[0-9]*[02468]$/
Explanation:
^ Start of line/string
[0-9] Any digit from zero to nine.
* Repeat the last token zero or more times.
[02468] Any even digit.
$ End of line/string.
To help you learn regular expressions I would recommend reading the Regular Expression Quick Start.
You may also see \d
used instead of [0-9]
. In some regular expression engines these are equivalent, but in others \d
also matches characters which are regarded as numerals in foreign countries.
For more information
As an exercise you could try to work out how to adjust this regular expression to disallow leading zeros. Hint: there are three types of digit: the first digit, the middle digits, the last digit. Remember that only the last digit must be present, the others are optional.