如何檢查字符串是否僅包含使用正則表達式指定字符?正則表達式來檢查字符串是否包含指定字符
例1:檢查是否字符串包含只字母和/或數字:
我的嘗試:
Regex rgx = new Regex("[^A-Za-z0-9]");
string s = "This is a string.";
if (rgx.IsMatch(s))
{
// true
}
else
{
// false;
}
上面的實例應該返回false(因爲我不想以允許期限),但它返回true。
實施例2:只有字母和/或號碼和/或空間和/或括號被允許:
Regex rgx = new Regex("[^A-Za-z0-9() ]");
string s = "This is a [string].";
if (rgx.IsMatch(s))
{
// true
}
else
{
// false;
}
同樣,第二實施例應該返回false(因爲我不想允許括號或句點),但是它返回true。