Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
246 views
in Technique[技术] by (71.8m points)

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
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"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...