简体   繁体   English

对AZ,0-9和-使用正则表达式和-?

[英]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.

相关问题 正则表达式:0-9 AZ az或其中任何一个&#39;!#$%&&#39;* + - / =?^ _`{|}〜 - Regular Expression: 0-9 A-Z a-z or any of these '!#$%&'*+-/=?^_`{|}~ 我有正则表达式将字符串拆分为单词,数字和标点符号列表。 如何制作列表中的“az”和“0-9”单个元素? - I have regex to split string to words, numbers and punctuation marks list. How to make “a-z” and “0-9” single elements of list? 正则表达式:仅限AZ字符 - Regex: A-Z characters only 在 C# 中将字符串从数字 0-9 增加到小写 az 到大写 AZ - Increment a string from numbers 0-9 to lowercase a-z to uppercase A-Z in C# C#Regex:检查“az”和“AZ” - C# Regex: Checking for “a-z” and “A-Z” 正则表达式仅允许使用0-9和-字符以及点(。) - Regex allow only 0-9 and the - character, and dot (.) 有没有办法找出C#中的字符串是否不包含数字和字符0-9和AZ? - Is there a way I can find out if a string in C# does not contain the numbers & characters 0-9 and A-Z? 如何创建az和0-9(最多8个字符)的字典并将其另存为.txt文件? - How can I create a dictionary with a-z and 0-9 up to 8 characters long and save it as a .txt file? 我的正则表达式中用于检查字符串的错误包含z或AZ - What the Error in my Regex to to check a string contains a-z or A-Z 如何获取正则表达式来检查字符串是否只包含字母字符[az]或[AZ]? - How can I get a regex to check that a string only contains alpha characters [a-z] or [A-Z]?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM