以下提供一些簡單的示例:
Code
string x = "1024";
string y = "+1024";
string z = "1,024";
string a = "1";
string b="-1024";
string c = "10000";
Regex r = new Regex(@"^\+?[1-9],?\d{3}$");
Console.WriteLine("x match count:" + r.Matches(x).Count);//1
Console.WriteLine("y match count:" + r.Matches(y).Count);//1
Console.WriteLine("z match count:" + r.Matches(z).Count);//1
Console.WriteLine("a match count:" + r.Matches(a).Count);//0
Console.WriteLine("b match count:" + r.Matches(b).Count);//0
Console.WriteLine("c match count:" + r.Matches(c).Count);//0
//匹配1000到9999的整數。
(5)擇一匹配
C#正則表達式中的 (|) 符號似乎沒有一個專門的稱謂,姑且稱之為“擇一匹配”吧。事實上,像[a-z]也是一種擇一匹配,只不過它只能匹配單個字符,而(|)則提供了更大的范圍,(ab|xy)表示匹配ab或匹配xy。注意“|”與“()”在此是一個整體。下面提供一些簡單的示例:
Code
string x = "0";
string y = "0.23";
string z = "100";
string a = "100.01";
string b = "9.9";
string c = "99.9";
string d = "99.";
string e = "00.1";
Regex r = new Regex(@"^\+?((100(.0+)*)|([1-9]?[0-9])(\.\d+)*)$");
Console.WriteLine("x match count:" + r.Matches(x).Count);//1
Console.WriteLine("y match count:" + r.Matches(y).Count);//1
Console.WriteLine("z match count:" + r.Matches(z).Count);//1
Console.WriteLine("a match count:" + r.Matches(a).Count);//0
Console.WriteLine("b match count:" + r.Matches(b).Count);//1
Console.WriteLine("c match count:" + r.Matches(c).Count);//1
Console.WriteLine("d match count:" + r.Matches(d).Count);//0
Console.WriteLine("e match count:" + r.Matches(e).Count);//0
//匹配0到100的數。最外層的括號內包含兩部分“(100(.0+)*)”,“([1-9]?[0-9])(\.\d+)*”,這兩部分是“OR”的關系,即正則表達式引擎會先嘗試匹配100,如果失敗,則嘗試匹配後一個表達式(表示[0,100)范圍中的數字)。
(6)特殊字符的匹配
下面提供一些簡單的示例:
Code
string x = "\\";
Regex r1 = new Regex("^\\\\$");
Console.WriteLine("r1 match count:" + r1.Matches(x).Count);//1
Regex r2 = new Regex(@"^\\$");
Console.WriteLine("r2 match count:" + r2.Matches(x).Count);//1
Regex r3 = new Regex("^\\$");
Console.WriteLine("r3 match count:" + r3.Matches(x).Count);//0
//匹配“\”
string x = "\"";
Regex r1 = new Regex("^\"$");
Console.WriteLine("r1 match count:" + r1.Matches(x).Count);//1
Regex r2 = new Regex(@"^""$");
Console.WriteLine("r2 match count:" + r2.Matches(x).Count);//1
//匹配雙引號