Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expression to match only odd or even number

Tags:

regex

I have a list of textual entries that a user can enter into the database and I need to validate these inputs with Regular Expressions because some of them are complex. One of the fields must have gaps in the numbers (i.e., 10, 12, 14, 16...). My question is, is there a Regex construct that would allow me to only match even or odd digit runs? I know I can pull this value out and do a division check on it, but I was hoping for a pure Regex solution to this if possible.

[Edit]

The solution I ended up using on this was an adaption of JaredPar's because in addition to needing only odd's or evens I also needed to constrain by a range (i.e., all even numbers between 10-40). Below is finished Regex.

^[123][02468]$

like image 662
James Avatar asked Mar 27 '09 21:03

James


People also ask

What's the difference between () and [] in regular expression?

[] denotes a character class. () denotes a capturing group. (a-z0-9) -- Explicit capture of a-z0-9 . No ranges.

How do I check if a number is only in regular expressions?

The \d can be used to match single number. Alternatively the [0-9] can be used to match single number in a regular expression. The [0-9] means between 0 and 9 a single number can match. The letters can not match in this case.

What is '?' In regular expression?

It means "Match zero or one of the group preceding this question mark." It can also be interpreted as the part preceding the question mark is optional. In above example '?' indicates that the two digits preceding it are optional. They may not occur or occur at the most once.

How do you match a regular expression?

To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" . You also need to use regex \\ to match "\" (back-slash).


1 Answers

Odd Numbers

"^\d*[13579]$" 

Even Numbers

"^\d*[02468]$" 

Run of Odds with a , and potential whitespace separator

"$\s*(\d*[13579]\s*,\s*)*\d*[13579]$" 

Run of Evens with a , and potential whitespace separator

"$\s*(\d*[02468]\s*,\s*)*\d*[02468]$" 
like image 74
JaredPar Avatar answered Oct 14 '22 04:10

JaredPar