简体   繁体   中英

Regular Expression to match only odd or even number

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 (ie, 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 (ie, all even numbers between 10-40). Below is finished Regex.

^[123][02468]$

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

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...

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM