正则表达式只匹配字母字符 [英] Regular Expression to match only alphabetic characters
问题描述
我想知道我是否能得到一个正则表达式来匹配一个只有字母字符的字符串,而且只有字母字符.
I was wondering If I could get a regular expression which will match a string that only has alphabetic characters, and that alone.
推荐答案
您可以使用以下 2 个变体中的任何一个:
You may use any of these 2 variants:
/^[A-Z]+$/i
/^[A-Za-z]+$/
匹配输入的 ASCII 字母字符串.
to match an input string of ASCII alphabets.
[A-Za-z]
将匹配所有字母(小写和大写).^
和$
将确保只匹配这些字母.
[A-Za-z]
will match all the alphabets (both lowercase and uppercase).^
and$
will make sure that nothing but these alphabets will be matched.
代码:
preg_match('/^[A-Z]+$/i', "abcAbc^Xyz", $m);
var_dump($m);
输出:
array(0) {
}
测试用例用于 OP 的评论,他希望仅当输入中存在 1 个或多个字母时才匹配.正如您在测试用例中看到的,匹配失败是因为输入字符串 abcAbc^Xyz
中有 ^
.
Test case is for OP's comment that he wants to match only if there are 1 or more alphabets present in the input. As you can see in the test case that matches failed because there was ^
in the input string abcAbc^Xyz
.
注意:请注意,上述答案只匹配 ASCII 字母,不匹配 Unicode 字符.如果要匹配 Unicode 字母,请使用:
Note: Please note that the above answer only matches ASCII alphabets and doesn't match Unicode characters. If you want to match Unicode letters then use:
/^\p{L}+$/u
这里,\p{L}
匹配来自任何语言的任何类型的字母
Here, \p{L}
matches any kind of letter from any language
这篇关于正则表达式只匹配字母字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!