A regex to match strings with alphanumeric, spaces and punctuation

后端 未结 3 1402
既然无缘
既然无缘 2020-12-15 19:25

I need a regular expression to match strings that have letters, numbers, spaces and some simple punctuation (.,!\"\'/$). I have ^[A-Za-z0-9 _]*[A-Za-z0-9

3条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-15 20:25

    Assuming from your regex that at least one alphanumeric character must be present in the string, then I'd suggest the following:

    /^(?=.*[A-Z0-9])[\w.,!"'\/$ ]+$/i
    

    The (?=.*[A-Z0-9]) lookahead checks for the presence of one ASCII letter or digit; the nest character class contains all ASCII alphanumerics including underscore (\w) and the rest of the punctuation characters you mentioned. The slash needs to be escaped because it's also used as a regex delimiter. The /i modifier makes the regex case-insensitive.

提交回复
热议问题