Alex Rivera | Logout

How can I get a regex to check that a string only contains alpha characters [a-z] or [A-Z]?

Asked 2009-06-13T09:12:12.630
17

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.

Edit
Report

1 Answer

4

The regular expression you are using is an alternation of [^a-z] and [^A-Z]. And the expressions [^…] mean to match any character other than those described in the character set.

So overall your expression means to match either any single character other than a-z or other than A-Z.

But you rather need a regular expression that matches a-zA-Z only:

[a-zA-Z]

And to specify the length of that, anchor the expression with the start (^) and end ($) of the string and describe the length with the {n,m} quantifier, meaning at least n but not more than m repetitions:

^[a-zA-Z]{0,25}$
answered 2009-06-13T09:28:24.057

Your Answer