Regex only allow letters and some characters

前端 未结 4 943
孤街浪徒
孤街浪徒 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:53

    - is special in character class. It is used to define a range as you've done with a-z.

    To match a literal - you need to either escape it or place it such that it'll not function as range operator:

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

    or

    ^[-a-zA-Z ,.()]*$
      ^ placing it at the beginning.
    

    or

    ^[a-zA-Z -,.()-]*$
                  ^ placing it at the end.
    

    and interestingly

    ^[a-z-A-Z -,.()]*$
         ^ placing in the middle of two ranges.
    

    In the final case - is place between a-z and A-Z since both the characters surrounding the -(the one which we want to treat literally) that is z and A are already involved in ranges, the - is treated literally again.

    Of all the mentioned methods, the escaping method is recommended as it makes your code easier to read and understand. Anyone seeing the \ would expect that an escape is intended. Placing the - at the beginning(end) will create problems if you later add a character before(after) it in the character class without escaping the - thus forming a range.

提交回复
热议问题