Regex only allow letters and some characters

前端 未结 4 1041
孤街浪徒
孤街浪徒 2021-02-14 18:04

I am attempting to create a regex that only allows letters upper or lowercase, and the characters of space, \'-\', \',\' \'.\', \'(\', and \')\'. This is what I have so far but

4条回答
  •  刺人心
    刺人心 (楼主)
    2021-02-14 18:34

    Well, there is an issue in that -, is being interpreted as a range, like a-z, allowing all characters from space to comma. Escape that and at least some of the bugs should be fixed.

    ^[a-zA-Z \-,.()]*$
    

    Strictly speaking, you should probably also escape the . and (), too, since those have special meaning in regular expressions. The Javascript regex engine (where I was testing) seems to interpret them literally within a [] context, anyway, but it's always far better to be explicit.

    ^[a-zA-Z \-,\.\(\)]*$
    

    However, this still shouldn't be allowing 0-9 digits, so your actual code that uses this regular expression probably has an issue, as well.

提交回复
热议问题