我有一个输入字符串,我想验证它包含:
仅限信件或 只有字母和数字或者 只能使用字母、数字或下划线
为了澄清,我在代码中有3种不同的情况,每种情况调用不同的验证。用c#实现这个最简单的方法是什么?
我有一个输入字符串,我想验证它包含:
仅限信件或 只有字母和数字或者 只能使用字母、数字或下划线
为了澄清,我在代码中有3种不同的情况,每种情况调用不同的验证。用c#实现这个最简单的方法是什么?
当前回答
你可以循环字符串的字符,并使用字符方法IsLetter检查 但是你也可以使用String方法IndexOfAny来搜索其他不应该在字符串中的字符。
其他回答
你可以循环字符串的字符,并使用字符方法IsLetter检查 但是你也可以使用String方法IndexOfAny来搜索其他不应该在字符串中的字符。
只有字母:
Regex.IsMatch(input, @"^[a-zA-Z]+$");
仅限字母和数字:
Regex.IsMatch(input, @"^[a-zA-Z0-9]+$");
只有字母、数字和下划线:
Regex.IsMatch(input, @"^[a-zA-Z0-9_]+$");
如果你是一个新手,那么你可以参考我的代码..我所做的就是开一张支票,这样我就只能得到字母和空白!您可以在第二个if语句之后重复for循环,以再次验证字符串
bool check = false;
Console.WriteLine("Please Enter the Name");
name=Console.ReadLine();
for (int i = 0; i < name.Length; i++)
{
if (name[i]>='a' && name[i]<='z' || name[i]==' ')
{
check = true;
}
else
{
check = false;
break;
}
}
if (check==false)
{
Console.WriteLine("Enter Valid Value");
name = Console.ReadLine();
}
最近,我在这个页面的帮助下对一个检查字符串中的字母的函数进行了性能改进。
我发现使用regex的解比使用Char的解慢30倍。IsLetterOrDigit检查。
我们不确定这些字母或数字包括,我们只需要拉丁字符,所以实现了基于反编译版本的Char的功能。IsLetterOrDigit函数。
下面是我们的解决方案:
internal static bool CheckAllowedChars(char uc)
{
switch (uc)
{
case '-':
case '.':
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
case 'G':
case 'H':
case 'I':
case 'J':
case 'K':
case 'L':
case 'M':
case 'N':
case 'O':
case 'P':
case 'Q':
case 'R':
case 'S':
case 'T':
case 'U':
case 'V':
case 'W':
case 'X':
case 'Y':
case 'Z':
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
return true;
default:
return false;
}
}
用法是这样的:
if( logicalId.All(c => CheckAllowedChars(c)))
{ // Do your stuff here.. }
我还没有看到使用模式匹配的解决方案:
public static bool ContainsOnlyLetters(this string input)
{
bool isValid = true;
for (int i = 0; isValid && i < input.Length; i++)
{
isValid &= input[i] is >= 'A' and <= 'Z' or >= 'a' and <= 'z';
}
return isValid;
}
或者如果你真的非常讨厌可读的代码:
public static bool ContainsOnlyLetters(this string input)
{
bool isValid = true;
for (int i = 0; i < input.Length && (isValid &= input[i] is >= 'A' and <= 'Z' or >= 'a' and <= 'z'); i++);
return isValid;
}