tags:

views:

2127

answers:

4

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 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]$

+13  A: 

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]$"
JaredPar
That matches even or odd numbers, but not "runs" of only even or only odd.
MarkusQ
@MarkusQ, thanks, added those cases.
JaredPar
Nice job, this did the trick, thanks.
James
+1  A: 

Do you mean something like:

/(\d*[02468](, *\d*[02468]))|(\d*[13579](, *\d*[13579]))/

or one of the three other possible interpretations of your question as worded?

MarkusQ
I think you also need to star the second subgroup in each group, no?
David Citron
+2  A: 

The Regex is actually not too hard to design, if you take into account that an even or odd number can be tested by only looking at the last digit, which need to be even or odd too. So the Regex for odd number runs could be:

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

Replace [13579] by [02468] for even numbers...

Varkhan
A: 

Actually, none of the above deals with the fact that an even number has no leading zeros.

Tobias W.