你可以嘗試這樣的事情,如果正則表達式是太慢:
using System;
using System.Linq;
namespace Demo
{
public static class Program
{
private static void Main()
{
string test = "thisIsTheStringToCheck!";
bool anyInvalidChars = !test.All(isValidChar);
Console.WriteLine(anyInvalidChars); // Prints True due to the "!" in the string.
}
private static bool isValidChar(char ch)
{
if ('A' <= ch && ch <= 'Z')
return true;
if ('a' <= ch && ch <= 'z')
return true;
switch (ch)
{
case '&':
case '$':
case '.':
case ',':
// Add more cases as required.
{
return true;
}
default:
{
return false;
}
}
}
}
}
或者,寫一個簡單的CharValidator
類使用像這樣:
using System;
using System.Linq;
namespace Demo
{
public static class Program
{
private static void Main()
{
CharValidator validator = new CharValidator();
validator.AddValidAsciiRange('A', 'Z');
validator.AddValidAsciiRange('a', 'z');
validator.AddValidAsciiChar('&');
validator.AddValidAsciiChar('$');
validator.AddValidAsciiChar('.');
validator.AddValidAsciiChar(',');
string test = "thisIsTheStringToCheck!";
bool anyInvalidChars = !validator.IsValidString(test);
Console.WriteLine(anyInvalidChars); // Prints True due to the "!" in the string.
}
}
public sealed class CharValidator
{
public void AddValidAsciiRange(char start, char end)
{
for (char ch = start; ch <= end; ++ch)
AddValidAsciiChar(ch);
}
public void AddValidAsciiChar(char ch)
{
if (ch >= 0 && ch <= 127)
_validAsciiChars[ch] = true;
}
public bool IsValidString(string str)
{
return str.All(IsValidChar);
}
public bool IsValidChar(char ch)
{
if (ch < 0 || ch >= 128)
return false;
return _validAsciiChars[ch];
}
private readonly bool[] _validAsciiChars = new bool[128];
}
}
那麼你的問題是什麼? – 2014-12-03 14:17:28
而不是使用預定義的正則表達式邏輯被實現爲接受輸入,考慮到Alphabets的ASCII碼,特殊字符。 @微軟DN。 – 2014-12-03 14:20:40
你使用正則表達式來檢查這個嗎? – 2014-12-03 14:21:26