Javascript 正则表达式只接受字母、空格和 ?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7373183/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript regex to accept only letters, spaces, and ?
提问by Jonathan Edgardo
I am looking for a Javascript regex to make sure the string contains only spaces, letters, and ? — case insensitively.
我正在寻找一个 Javascript 正则表达式来确保字符串只包含空格、字母和 ? - 不区分大小写。
I already tried: /^[A-Za-z _]*[A-Za-z][A-Za-z _]*$/
but it fails to accept ?
.
我已经尝试过:/^[A-Za-z _]*[A-Za-z][A-Za-z _]*$/
但它无法接受?
.
回答by Benjamin Udink ten Cate
/^[?A-Za-z _]*[?A-Za-z][?A-Za-z _]*$/
and
和
/^[\u00F1A-Za-z _]*[\u00F1A-Za-z][\u00F1A-Za-z _]*$/
should work.
应该管用。
Javascript regex supports \u0000
through \uFFFF
.
Javascript 正则表达式支持\u0000
通过\uFFFF
.
回答by xanatos
If you simply want that caracter, insert it in the Regex, like [A-Za-z?? ]
. Otherwise use a Unicode-knowing Regex library for Javascript like http://xregexp.com/. Sadly JS Regexes don't support Unicode compliant character classes (like \p{L}
in C# regexes)
如果您只是想要该字符,请将其插入正则表达式中,例如[A-Za-z?? ]
. 否则,请为 Javascript 使用支持 Unicode 的 Regex 库,例如http://xregexp.com/。遗憾的是 JS 正则表达式不支持 Unicode 兼容的字符类(如\p{L}
在 C# 正则表达式中)
回答by Chinmay Kanchi
You need to use a character class.
您需要使用字符类。
/[A-Za-z ?]+/