Regex expression not working with once or none

前端 未结 2 1740
别那么骄傲
别那么骄傲 2020-12-04 04:29

Below is my regex:

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

But it throws an error at -. I am using ?, which should al

相关标签:
2条回答
  • 2020-12-04 04:48

    Try escaping - with \ and remove [ and ]:

    ^4\d{3}\-?\d{4}\-?\d{4}\-?\d{4}$
    
    0 讨论(0)
  • 2020-12-04 05:00

    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.

    0 讨论(0)
提交回复
热议问题