字母表、下划线、连字符、撇号的正则表达式 [英] Regular expression for alpahbet,underscore,hyphen,apostrophe only
本文介绍了字母表、下划线、连字符、撇号的正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想要一个只接受字母、连字符、撇号、下划线的正则表达式.我试过了
I want a regular expression that accept only alphabets,hyphen,apostrophe,underscore. I tried
/^[ A-Za-z-_']*$/
但它不起作用.请帮忙.
but its not working. Please help.
推荐答案
您的正则表达式错误.试试这个:
Your regex is wrong. Try this:
/^[0-9A-Za-z_@'-]+$/
或
/^[\w@'-]+$/
连字符需要在字符类中的第一个或最后一个位置以避免转义.此外,如果不允许空字符串,则使用 +
(1 或更多)代替 *
(0 或更多)
Hyphen needs to be at first or last position inside a character class to avoid escaping. Also if empty string isn't allowed then use +
(1 or more) instead of *
(0 or more)
说明:
^ 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
这篇关于字母表、下划线、连字符、撇号的正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文