简体   繁体   English

正则表达式只匹配奇数或偶数

[英]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...).字段之一的数字必须有间隙(即 10、12、14、16...)。 My question is, is there a Regex construct that would allow me to only match even or odd digit runs?我的问题是,是否有一个 Regex 构造允许我只匹配偶数或奇数运行? 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).我最终使用的解决方案是对 JaredPar 的改编,因为除了只需要奇数或偶数之外,我还需要限制一个范围(即 10-40 之间的所有偶数)。 Below is finished Regex.下面是完成的正则表达式。

^[123][02468]$ ^[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使用 , 和潜在的空格分隔符运行 Evens

"$\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...对于偶数,将 [13579] 替换为 [02468]...

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?或者你的问题的其他三种可能的解释之一?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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