Johnrad
Johnrad

Reputation: 2655

Regular Expression for all positive even numbers

I am currently enrolled in Translation Applications and we are working on regular expressions. This IS a homework problem. I have been at this one for a while I am just confused. I don't want just an answer, an explanation would be greatly appreciated just making sure that I learn it.

I just need a regular expression for all even numbers, leading 0's is okay. Here is some examples of what I need... (Examples, 0, 00, ... 2, 4, 6, 8, 10, 010, 12, ...)

Thanks.

Upvotes: 3

Views: 8055

Answers (2)

RC.
RC.

Reputation: 28267

/\d*[02468]$/         

Basically you want to match all numbers up to the last one which is what the \d* does. (\d* reads match zero or more numbers) Then the last number must be either a 0,2,4,6, or an 8. This is accomplished with the [02468] and the $ anchors it to the end of line. When you put square brackets around characters it states that you want to only match this list of characters. Another example would be if you had a regex of /[abc]/, you would match a string if it had an 'a', 'b', or 'c' within it.

Upvotes: 4

Mark Byers
Mark Byers

Reputation: 838876

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.

Upvotes: 8

Related Questions