本文介绍了正则表达式:匹配 x 次或 y 次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设一个模式连续出现 3 或 6 次,我需要匹配它.我能得到的最接近的是 \d{3,6} 之类的东西,但这并不能完全满足我的需求.
Lets say I need to match a pattern if it appears 3 or 6 times in a row. The closest I can get is something like \d{3,6} but that doesn't quite do what I need.
'123' 应该匹配
'123456' 应该匹配
'1234' 不应该匹配
'123' should match
'123456' should match
'1234' should not match
推荐答案
^(\d{3}|\d{6})$
你必须有某种终止符,否则 \d{3}
将匹配 1234.这就是我把 ^ 和 $ 放在上面的原因.一种替代方法是使用环视:
You have to have some sort of terminator otherwise \d{3}
will match 1234. That's why I put ^ and $ above. 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.
这篇关于正则表达式:匹配 x 次或 y 次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!