简体   繁体   中英

Using Regex.match on char

How do I use for example this line:

Regex.Matches(str,@"[a-zA-Z]");

that instead of the str I will have a char?

It seems that you want to test if a character is a letter. You do not need a regular expression to do that. Instead you can use the following:

var isLetter = Char.IsLetter(ch);

However, this will return true for all UNICODE letters, not only AZ, eg also accented letters like É or other letters like Æ and 你.

If you want to only test for AZ (upper and lower case) you can use this simple test:

var upperCaseCh = Char.ToUpperInvariant(ch);
var isLetter = 'A' <= upperCaseCh && upperCaseCh <= 'Z';

I'd rather use the static functions of the char class or use the comparison operators, ie

var test = 'a' <= c && c <= 'z';

The static methods can give you the character class, eg letter, digit or whitespace.

You can call ToString on character and then use that like:

char ch = 'c';
Regex.Matches(ch.ToString(),@"[a-zA-Z]");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM