標籤:轉義 存在 判斷 net drivers options value xxx path
1.指定字元出現多次用 ([a-zA-Zxxx]+),不是 (a-zA-Zxxx)+,後面那個是這一組出現多次,對於貪婪模式來說可能有些問題
2.貪婪模式,最好後面跟著一個結束標識符
①. 測試,輸出結果是1111。11。111。111111。 //貪婪模式,針對於這個對於這個正則(.)的儘可能多的去匹配,這一段字元都符合的就取下來 string msg = "1111。11。111。111111。"; //.+,預設按照貪婪模式來匹配,儘可能多的去匹配。 Match match = Regex.Match(msg, ".+"); Console.WriteLine(match.Value); Console.ReadKey();②1111。11。111。111111。,使用Match,\d+只匹配到1111,因為對於這個正則,第一個出現的1111,不會貪婪到最後,因為。不是數字,對於後面那段來說不匹配了③終止貪婪模式,結果是1 string msg = "1111。11。111。111111。"; //.+,預設按照貪婪模式來匹配,儘可能多的去匹配。 //當在“限定符”後使用?的時候,表示終止貪婪模式 //當終止貪婪模式之後,會按照指定正則儘可能少的匹配。 Match match = Regex.Match(msg, ".+?"); Console.WriteLine(match.Value); Console.ReadKey();//注意:千萬不要寫成(.+)?,這樣結果是1111。11。111。111111。,因為括弧改變正則雲演算法優先順序問題,先計算(.+)這個正則,所以全部匹配出來了,再計算?。除非是這樣寫(.+?)④不要使用*,因為這個意思是零次或者多次,相當於{0,},會匹配不到結果的 string str = "abbb"; Match match = Regex.Match(str, ".*?"); Console.WriteLine(match.Value); Console.ReadKey();⑤ 結果是:1111。11。111。111111。string msg = "1111。11。111。111111。"; Match match = Regex.Match(msg, ".+。"); Console.WriteLine(match.Value); Console.ReadKey();⑥結果是1111。,.+?阻止了貪婪模式,匹配到了1111,加上後面的。 string msg = "1111。11。111。111111。1。1。1。"; Match match = Regex.Match(msg, ".+?。"); Console.WriteLine(match.Value); Console.ReadKey();⑦結果是1111。11。111。111111。1。1。1。 string msg = "1111。11。111。111111。1。1。1。"; Match match = Regex.Match(msg, "(.+。)"); Console.WriteLine(match.Value); Console.ReadKey();⑧匹配名字,因為後面都有。句號,可用來作為標誌的分隔字元 string msg = "大家好。我們是A.B.C。我是A。我是B。我是C。我是XXX。我是X.X.X。我是★XX★。嗚嗚。fffff"; MatchCollection matches = Regex.Matches(msg, "我是(.+?)。"); foreach (Match item in matches) { Console.WriteLine(item.Groups[1].Value); } Console.ReadKey();⑨提取檔案中的檔案名稱 string path = @"C:\Windows\System32\drivers\etc\hosts"; //此處因為有“貪婪模式”的存在,所以Regex中的 \\ 肯定匹配的是檔案路徑中的最後一個 Match match = Regex.Match(path, @".+\\(.+)"); Console.WriteLine(match.Groups[1].Value); Console.ReadKey();
3..net預設使用的是Unicode匹配模式‘’
①結果是true,連全形符號都匹配string msg = "123";//123 123bool b = Regex.IsMatch(msg, @"\d+"); ②結果是false string msg = "123";//123 123//這個可以準確判斷是ASCII字元123,不包含unicode字元123,其實就是在IME中使用“全形”輸出123 bool b = Regex.IsMatch(msg, @"\d+", RegexOptions.ECMAScript);③ true string msg = "abd097776_432ERWEWR__你好你好你好你好你好"; bool b = Regex.IsMatch(msg, @"^\w+$"); ④false string msg = "abd097776_432ERWEWR__你好你好你好你好你好"; bool b = Regex.IsMatch(msg, @"^\w+$", RegexOptions.ECMAScript);
4、 關於C#字串中的\轉義問題 與 Regex中的\的轉義問題。
①//string reg = "\d"; //此時c#會認為\是一個字串的轉義符。如: 此時運行完畢後其實就是正常字元 \d string reg = "\\\\d"; //此時c#會認為\是一個字串的轉義符。 bool b = Regex.IsMatch(@"\d", reg); //reg → \\d→ \d,2重轉義 Console.WriteLine(b);結果是true,reg 就是正常字元\\d,\\d轉義前面的\就成普通的字元\d② Console.WriteLine("a\\\\tb"); a\\tb
C#:正則注意點