简体   繁体   English

正则表达式:匹配x次或y次

[英]regular expressions: match x times OR y times

Lets say I need to match a pattern if it appears 3 or 6 times in a row. 假设我需要匹配一个模式,如果它连续出现3或6次。 The closest I can get is something like \\d{3,6} but that doesn't quite do what I need. 我能得到的最接近的是\\ d {3,6}之类的东西,但这并不能完全满足我的需要。

'123' should match '123'应该匹配
'123456' should match '123456'应该匹配
'1234' should not match '1234'不匹配

^(\d{3}|\d{6})$

You have to have some sort of terminator otherwise \\d{3} will match 1234. That's why I put ^ and $ above. 您必须具有某种终止符,否则\\d{3}将匹配1234。这就是为什么我在上面加上^和$。 One alternative is to use lookarounds: 一种替代方法是使用环视:

(?<!\d)(\d{3}|\d{6})(?!\d)

to make sure it's not preceded by or followed by a digit (in this case). 以确保它的前面没有数字(在这种情况下)。 More in Lookahead and Lookbehind Zero-Width Assertions . 更多有关零宽断言的前瞻性和后瞻性

How about: 怎么样:

(\d\d\d){1,2}

although you'll also need guards at either end which depend on your RE engine, something like: 尽管您还需要在两端依赖于RE引擎的防护措施,例如:

[^\d](\d\d\d){1,2}[^\d]

or: 要么:

^(\d\d\d){1,2}$

First one matches 3, 6 but also 9, 12, 15, .... Second looks right. 第一个匹配3、6,但也匹配9、12、15...。第二个看上去正确。 Here's one more twist: 这里还有一个转折点:

\d{3}\d{3}?

For this case we can get away with this crafty method: 对于这种情况,我们可以摆脱这种狡猾的方法:

Clean Implementation 清洁实施

/(\d{3}){1,2}/
/(?:\d{3}){1,2}/

How?! 怎么样?!

This works because we're looking for multiples of three that are consecutive in this case. 之所以可行,是因为在这种情况下,我们正在寻找三个连续的倍数。

Note : There's no reason to capture the group for this case so I add the ?: non capture group flag to the capture group. 注意 :在这种情况下没有理由捕获该组,因此我将?: non capture group标志添加到捕获组。

This is similar to paxdiablo implementation, but slightly cleaner. 这类似于paxdiablo实现,但稍微干净一些。

Matching Hex 配套六角

I was doing something similar for matching on basic hex colors since they could be 3 or 6 in length. 我在为基本十六进制颜色进行匹配方面做了类似的事情,因为它们的长度可能是3或6。 This allowed me to keep my hex color checker's matching DRY'd up ie: 这使我可以保持十六进制颜色检查器匹配的DRY'd即:

/^0x(?:[\da-f]{3}){1,2}$/i

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

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