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

时间:2021-09-25 21:37:58

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.

我有一个用户可以输入到数据库的文本条目列表,我需要用正则表达式验证这些输入,因为其中有些是复杂的。其中一个字段必须在数字中有空隙(例如。,10,12,14,16……我的问题是,是否有一个Regex构造允许我只匹配偶数或奇数位运行?我知道我可以把这个值取出来,做一个除法检查,但是我希望如果可能的话,可以用一个纯正则表达式来解决这个问题。

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

我最后使用的解决方案是对JaredPar的改编,因为除了只需要奇数或偶数之外,我还需要用一个范围来约束(例如)。,都是10-40之间的偶数)。下面是正则表达式完成。

^[123][02468]$

^[123][02468]美元

3 个解决方案

#1


50  

Odd Numbers

奇数

"^\d*[13579]$"

Even Numbers

偶数

"^\d*[02468]$"

Run of Odds with a , and potential whitespace separator

与a和潜在的空白分隔符之间的冲突。

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

Run of Evens with a , and potential whitespace separator

运行带有潜在空格分隔符的Evens

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

#2


5  

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:

Regex实际上并不是很难设计的,如果您考虑到一个偶数或奇数可以通过只查看最后一个数字来测试,这个数字也需要是偶数或奇数。所以奇数次运行的Regex可以是:

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

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

把[13579]换成[02468]偶数……

#3


2  

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?

或者你的问题的其他三种可能的解释中的一种?

#1


50  

Odd Numbers

奇数

"^\d*[13579]$"

Even Numbers

偶数

"^\d*[02468]$"

Run of Odds with a , and potential whitespace separator

与a和潜在的空白分隔符之间的冲突。

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

Run of Evens with a , and potential whitespace separator

运行带有潜在空格分隔符的Evens

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

#2


5  

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:

Regex实际上并不是很难设计的,如果您考虑到一个偶数或奇数可以通过只查看最后一个数字来测试,这个数字也需要是偶数或奇数。所以奇数次运行的Regex可以是:

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

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

把[13579]换成[02468]偶数……

#3


2  

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?

或者你的问题的其他三种可能的解释中的一种?