我怎样才能得到一个正则表达式来检查一个字符串只包含字母字符[A-Z]或[A-Z]? [英] How can I get a regex to check that a string only contains alpha characters [a-z] or [A-Z]?
问题描述
我试图创建一个正则表达式来验证一个给定的字符串只有字母字符a-z或A-Z。该字符串可长达25个字母。 (我不知道,如果正则表达式可以检查字符串的长度)
例子:
1 ABCDEF=真;
2 a2bdef= FALSE
;
3 333= FALSE;
4 J=真;
5 aaaaaaaaaaaaaaaaaaaaaaaaaa= FALSE;
// 26个字母
下面是我迄今为止...无法弄清楚什么是错了,但
正则表达式alphaPattern =新的正则表达式([^ A-Z] | [^ A-Z]);
我想这将意味着该字符串可以包含A-Z只有大写或小写字母,但是当我把它匹配所有的字母返回false字符串...
此外,关于使用正则表达式与其他验证方法将会大大AP preciated效率的任何建议。
正则表达式lettersOnly =新的正则表达式(^ [A-ZA-Z] {1,25} $);
-
^
表示开始于字符串开始匹配 -
[A-ZA-Z]
表示匹配小写和大写字母A-Z -
{1,25}
表示匹配previous项目(字符类,见上文)1至25倍 -
$
表示只有当光标在字符串结尾匹配
I'm trying to create a regex to verify that a given string only has alpha characters a-z or A-Z. The string can be up to 25 letters long. (I'm not sure if regex can check length of strings)
Examples:
1. "abcdef" = true;
2. "a2bdef" = false
;
3. "333" = false;
4. "j" = true;
5. "aaaaaaaaaaaaaaaaaaaaaaaaaa" = false;
//26 letters
Here is what I have so far... can't figure out what's wrong with it though
Regex alphaPattern = new Regex("[^a-z]|[^A-Z]");
I would think that would mean that the string could contain only upper or lower case letters from a-z, but when I match it to a string with all letters it returns false...
Also, any suggestions regarding efficiency of using regex vs. other verifying methods would be greatly appreciated.
Regex lettersOnly = new Regex("^[a-zA-Z]{1,25}$");
^
means "begin matching at start of string"[a-zA-Z]
means "match lower case and upper case letters a-z"{1,25}
means "match the previous item (the character class, see above) 1 to 25 times"$
means "only match if cursor is at end of string"
这篇关于我怎样才能得到一个正则表达式来检查一个字符串只包含字母字符[A-Z]或[A-Z]?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!