How can I get a regex to check that a string only

2019-01-13 19:02发布

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.

7条回答
叛逆
2楼-- · 2019-01-13 19:33

Do I understand correctly that it can only contain either uppercase or lowercase letters?

new Regex("^([a-z]{1,25}|[A-Z]{1,25})$")

A regular expression seems to be the right thing to use for this case.

By the way, the caret ("^") at the first place inside a character class means "not", so your "[^a-z]|[^A-Z]" would mean "not any lowercase letter, or not any uppercase letter" (disregarding that a-z are not all letters).

查看更多
登录 后发表回答