我有一个输入字符串,我想验证它包含:
仅限信件或 只有字母和数字或者 只能使用字母、数字或下划线
为了澄清,我在代码中有3种不同的情况,每种情况调用不同的验证。用c#实现这个最简单的方法是什么?
我有一个输入字符串,我想验证它包含:
仅限信件或 只有字母和数字或者 只能使用字母、数字或下划线
为了澄清,我在代码中有3种不同的情况,每种情况调用不同的验证。用c#实现这个最简单的方法是什么?
当前回答
我还没有看到使用模式匹配的解决方案:
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;
}
其他回答
你可以循环字符串的字符,并使用字符方法IsLetter检查 但是你也可以使用String方法IndexOfAny来搜索其他不应该在字符串中的字符。
我还没有看到使用模式匹配的解决方案:
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;
}
对于那些不愿意使用Regex并且使用。net 2.0框架(也就是没有LINQ)的人:
只有字母:
public static bool IsAllLetters(string s)
{
foreach (char c in s)
{
if (!Char.IsLetter(c))
return false;
}
return true;
}
只有数字:
public static bool IsAllDigits(string s)
{
foreach (char c in s)
{
if (!Char.IsDigit(c))
return false;
}
return true;
}
只有数字或字母:
public static bool IsAllLettersOrDigits(string s)
{
foreach (char c in s)
{
if (!Char.IsLetterOrDigit(c))
return false;
}
return true;
}
只有数字、字母或下划线:
public static bool IsAllLettersOrDigitsOrUnderscores(string s)
{
foreach (char c in s)
{
if (!Char.IsLetterOrDigit(c) && c != '_')
return false;
}
return true;
}
bool result = input.All(Char.IsLetter);
bool result = input.All(Char.IsLetterOrDigit);
bool result = input.All(c=>Char.IsLetterOrDigit(c) || c=='_');
请找到验证字符是字母、数字还是空格的方法,否则附加下划线 (可根据需要随意修改)
public String CleanStringToLettersNumbers(String data)
{
var result = String.Empty;
foreach (var item in data)
{
var c = '_';
if ((int)item >= 97 && (int)item <= 122 ||
(int)item >= 65 && (int)item <= 90 ||
(int)item >= 48 && (int)item <= 57 ||
(int)item == 32)
{
c = item;
}
result = result + c;
}
return result;
}