What is the difference between the two regex pattern

前端 未结 2 1997
深忆病人
深忆病人 2021-01-20 20:11

I was trying to validate a company name in a web application and had this regex pattern

^[a-zA-Z_\'\\\\s,;.-0-9]{1,100}$

The above pattern

2条回答
  •  攒了一身酷
    2021-01-20 20:57

    - is a special character in character classes and thus .-0-9 is ambiguous and probably gets the meaning . to 0 and - and 9, so essentially the characters ./09-.

    To include a hyphen-minus in a character class you'd either have to escape it or place it at the start or end of the character class (which is what you're doing in the second regex, maybe by accident).

    Edited to add: Above guess seems to be correct, at least for .NET's regex engine:

    PS> [char[]](32..127) -match '[a-zA-Z_''\s,;.-0-9]'
    
    '
    ,
    -
    .
    /
    0
    9
    ;
    A
    ...
    

提交回复
热议问题