我想要一个只接受字母、连字符、撇号、下划线的正则表达式。我试过
/^[ A-Za-z-_']*$/
Run Code Online (Sandbox Code Playgroud)
但它不工作。请帮忙。
你的正则表达式是错误的。尝试这个:
/^[0-9A-Za-z_@'-]+$/
Run Code Online (Sandbox Code Playgroud)
或者
/^[\w@'-]+$/
Run Code Online (Sandbox Code Playgroud)
连字符需要在字符类中的第一个或最后一个位置以避免转义。此外,如果不允许使用空字符串,则使用+(1 或更多)而不是*(0 或更多)
解释:
^ assert position at start of the string
[\w@'-]+ match a single character present in the list below
Quantifier: Between one and unlimited times, as many times as possible
\w match any word character [a-zA-Z0-9_]
@'- a single character in the list @'- literally
$ assert position at end of the string
Run Code Online (Sandbox Code Playgroud)