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]$
[] denotes a character class. () denotes a capturing group. (a-z0-9) -- Explicit capture of a-z0-9 . No ranges.
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.
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.
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).
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]$"
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