Javascript 仅用于字符 az, AZ 的正则表达式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3532053/
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
Regular expression for only characters a-z, A-Z
提问by Shantanu Gupta
I don't know how to create a regular expression in JavaScript or jQuery.
我不知道如何在 JavaScript 或 jQuery 中创建正则表达式。
I want to create a regular expression that will check if a string contains only characters between a-z and A-Z with any arrangement.
我想创建一个正则表达式,该表达式将检查字符串是否仅包含 az 和 AZ 之间的任何排列的字符。
EDIT
编辑
When I tried to make regex
当我尝试制作正则表达式时
/^[a-zA-Z\s]+$/
to accept white spaces as well. It is not working. What could be the mistake?
也接受空格。它不工作。可能是什么错误?
I am testing my regular expression at JavaScript RegExp Example: Online Regular Expression Tester.
我正在JavaScript RegExp Example: Online Regular Expression Tester测试我的正则表达式。
回答by NullUserException
/^[a-zA-Z]*$/
Change the *to +if you don't want to allow empty matches.
更改*到+,如果你不希望允许空匹配。
References:
参考:
Character classes ([...]), Anchors (^and $), Repetition (+, *)
字符类 ( [...])、锚点 ( ^and $)、重复 ( +, *)
The /are just delimiters, it denotes the start and the end of the regex. One use of this is now you can use modifierson it.
的/只是分隔符,它表示开始和正则表达式的结束。一种用途是现在您可以在其上使用修饰符。
回答by Hooray Im Helping
Piggybacking on what the other answers say, since you don't know how to do them at all, here's an example of how you might do it in JavaScript:
捎带其他答案所说的内容,因为您根本不知道如何做,这里有一个示例,说明您如何在 JavaScript 中做到这一点:
var charactersOnly = "This contains only characters";
var nonCharacters = "This has _@#*($()*@#$(*@%^_(#@!$ non-characters";
if (charactersOnly.search(/[^a-zA-Z]+/) === -1) {
alert("Only characters");
}
if (nonCharacters.search(/[^a-zA-Z]+/)) {
alert("There are non characters.");
}
The /starting and ending the regular expression signify that it's a regular expression. The searchfunction takes both strings and regexes, so the /are necessary to specify a regex.
/正则表达式的开始和结束表示它是一个正则表达式。该search函数采用字符串和/正则表达式,因此需要指定正则表达式。
From the MDN Docs, the function returns -1if there is no match.
从MDN Docs,-1如果没有匹配,该函数返回。
Also note: that this works for onlya-z, A-Z. If there are spaces, it will fail.
另请注意:这仅适用于az、AZ。如果有空格,它将失败。
回答by Ollie Edwards
/^[a-zA-Z]+$/
Off the top of my head.
离开我的头顶。
Edit:
编辑:
Or if you don't like the weird looking literal syntax you can do it like this
或者如果你不喜欢看起来很奇怪的文字语法,你可以这样做
new RegExp("^[a-zA-Z]+$");
回答by RobertPitt
With POSIX Bracket Expressions (not supported by Javascript) it can be done this way:
使用 POSIX 括号表达式(Javascript 不支持),可以通过以下方式完成:
/[:alpha:]+/
Any alpha character A to Z or a to z.
任何字母字符 A 到 Z 或 a 到 z。
or
或者
/^[[:alpha:]]+$/s
to match strictly with spaces.
与空格严格匹配。

![Javascript Vue JS 返回 [__ob__: Observer] 数据而不是我的对象数组](/res/img/loading.gif)