C#中使用正則所需要引用的命名空間是 using System.Text.RegularExpressions
它包含了8個類,用得最多是的Regex,Regex不僅可以用來創建正則表達式,而且提供了很多有用的方法。
首先來看一下如何創建一個Regex對象:
new Regex(string pattern)
new Regex(string pattern,RegexOptions options)
第一個參數是正則表達式字符串,第二個參數正則配置的選項,有以下幾種選項:
IgnoreCase //是匹配忽略大小寫 默認情況區分大小寫
RightToLeft //從右到左查找字符串 默認是從左到右
None //不設定標志 這是默認選項,就是不設置第2個參數 表示區分大小寫 從左到右
MultiLine //指定了^和$可以匹配行的開頭和結尾,也就是說使用了換行分割,每一行能得到不同的匹配
SingleLine //規定特殊字符"."匹配任一字符,換行符除外。默認情況下特殊字符"."不匹配換行
IgnoreCase的例子
string test = "Abcccccc";Regex reg = new Regex("abc");Console.WriteLine(reg.IsMatch(test)); //falseRegex reg1 = new Regex("abc",RegexOptions.IgnoreCase); //不區分大小寫Console.WriteLine(reg1.IsMatch(test));//true
RightToLeft的例子
string test = "vvv123===456vvv";Regex reg = new Regex("http://d+");// 123 從左到右 匹配連續數字Console.WriteLine(reg.Match(test));Regex reg1 = new Regex("http://d+",RegexOptions.RightToLeft);Console.WriteLine(reg1.Match(test));// 456 從右到左 匹配連續數字
MultiLine的例子
StringBuilder input = new StringBuilder();input.AppendLine("A bbbb A");input.AppendLine("C bbbb C");string pattern = @"^/w";Console.WriteLine(input.ToString());MatchCollection matchCol = Regex.Matches(input.ToString(), pattern, RegexOptions.Multiline);foreach (Match item in matchCol){ Console.WriteLine("結果:{0}", item.Value);}
這時可能有人會問了,如果既想忽略大小寫,又想匹配多行,該怎么辦呢,就是兩種選項同時滿足的情況,該如何做呢?
呵呵,當然是有方法的的,只要用豎線將兩個選項隔開就可以了,如下舉例
Regex.Matches(input.ToString(), pattern, RegexOptions.IgnoreCase | RegexOptions.Multiline);
新聞熱點
疑難解答