[英]Using regex for A-Z, 0-9, - and dot?
I have a long method like this, that has hard coded each character. 我有一个很长的方法,像这样,已经对每个字符进行了硬编码。 Is there a way to use
Regex
for something like this, to make it much shorter , and much easier ? 有没有办法使用
Regex
的东西,使其更短 ,更容易 ?
private static bool IsValid(char character)
{
return new List<char>(new[]
{
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',
'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x',
'y', 'z', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '-', '.'
}).Contains(character);
}
I suggest to check ranges , eg 我建议检查范围 ,例如
private static bool IsValid(char character) {
return character >= 'a' && character <= 'z' || // letters
character >= '0' && character <= '9' || // digits
character == '-' || // special characters
character == '.';
}
Techically, you can use regular expressions but it is an overshoot : 从技术上讲,您可以使用正则表达式,但这是一个过冲 :
private static bool IsValid(char character) {
return Regex.IsMatch(character.ToString(), @"[a-z0-9\.\-]");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.