本文介绍了正则表达式只匹配奇数或偶数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用户可以输入数据库的文本条目列表,我需要使用正则表达式验证这些输入,因为其中一些很复杂.其中一个字段的数字必须有间隙(即 10、12、14、16...).我的问题是,是否有一个 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.

我最终使用的解决方案是对 JaredPar 的改编,因为除了只需要奇数或偶数之外,我还需要限制一个范围(即 10-40 之间的所有偶数).下面是完成的正则表达式.

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

推荐答案

奇数

"^\d*[13579]$"

偶数

"^\d*[02468]$"

带有 , 和潜在空格分隔符的赔率运行

Run of Odds with a , and potential whitespace separator

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

使用 , 和潜在的空格分隔符运行 Evens

Run of Evens with a , and potential whitespace separator

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

这篇关于正则表达式只匹配奇数或偶数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 01:17