Regex expression not working with once or none

泪湿孤枕 提交于 2019-11-26 18:41:00

问题


Below is my regex:

[^4\d{3}-?\d{4}-?\d{4}-?\d{4}$]

But it throws an error at -. I am using ?, which should allows - to appear zero or one time. Why it is giving errors?


回答1:


The problem with the regex is that the pattern is enclosed with [ and ] that are treated as character class markers (see Character Classes or Character Sets):

With a "character class", also called "character set", you can tell the regex engine to match only one out of several characters. Simply place the characters you want to match between square brackets. If you want to match an a or an e, use [ae].

In character classes, - creates ranges between literal characters. In your case, these ranges are not valid (go from a character with higher values to those with lower values) since the {4} and other subpatterns were treated as separate characters, not special constructs:

So, all you need to do is remove the [ and ] on both sides:

^4\d{3}-?\d{4}-?\d{4}-?\d{4}$

See regex demo.




回答2:


Try escaping - with \ and remove [ and ]:

^4\d{3}\-?\d{4}\-?\d{4}\-?\d{4}$


来源:https://stackoverflow.com/questions/34765780/regex-expression-not-working-with-once-or-none

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