Regex to match a digit two or four times

夙愿已清 提交于 2019-12-18 10:31:58

问题


It's a simple question about regular expressions, but I'm not finding the answer.

I want to determine whether a number appears in sequence exactly two or four times. What syntax can I use?

\d{what goes here?}

I tried \d{2,4}, but this expression accepts three digits as well.


回答1:


There's no specific syntax for that, but there are lots of ways to do it:

(?:\d{4}|\d{2})    <-- alternation: four digits or two
\d{2}(?:\d{2})?    <-- two digits, and optionally two more
(?:\d{2}){1,2}     <-- two digits, times one or two


来源:https://stackoverflow.com/questions/8177143/regex-to-match-a-digit-two-or-four-times

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!