輸入的字符串:Provider=ASEOLEDB.1;Initial Catalog=big;User ID=sa;Persist Security Info=False;Server Name=192.168.2.168:5000;Character Set=cp850
private string SplitCharset(string s, string charset) { Regex rSplit = new Regex(";"); Regex r = new Regex(s); Match m = r.Match(charset); if (m.Success) { MatchCollection mc = rSplit.Matches(charset.Substring(m.Index + s.Length)); if (mc.Count > 0) { return charset.Substring(m.Index + s.Length, mc[0].Index); } else { return charset.Substring(m.Index + s.Length, charset.Length - (m.Index + s.Length)); } } else return ""; }
使用靜態Match方法,可以得到源中第一個匹配模式的連續子串。
例如:
Match myMatch = Regex.Match("asdfasdfasdf", @"\basdf\B");
Console.WriteLine(myMatch.Value);
程序將輸出asdf(這里匹配了文本中第二個asdf)
靜態的Match方法有2個重載,分別是
Regex.Match(string input, string pattern);
Regex.Match(string input, string pattern, RegexOptions options);
第一種
重載的參數表示:輸入、模式
第二種
重載的參數表示:輸入、模式、RegexOptions枚舉的“按位或”組合。
RegexOptions枚舉的有效值是:
Complied表示編譯此模式
CultureInvariant表示不考慮文化背景
ECMAScript表示符合ECMAScript,這個值只能和IgnoreCase、Multiline、Complied連用
ExplicitCapture表示只保存顯式命名的組
IgnoreCase表示不區分輸入的大小寫
IgnorePatternWhitespace表示去掉模式中的非轉義空白,並啟用由#標記的注釋
Multiline表示多行模式,改變
元字符^和$的含義,它們可以匹配行的開頭和結尾
None表示無設置,此枚舉項沒有意義
RightToLeft表示從右向左掃描、匹配,這時,靜態的Match方法返回從右向左的第一個匹配
Singleline表示單行模式,改變
元字符.的意義,它可以匹配換行符
注意:Multiline在沒有ECMAScript的情況下,可以和Singleline連用。Singleline和Multiline不互斥,但是和ECMAScript互斥。
靜態的Matches方法
這個方法的
重載形式同靜態的Match方法,返回一個MatchCollection,表示輸入中,匹配模式的匹配的集合。
靜態的IsMatch方法
此方法返回一個bool,
重載形式同靜態的Matches,若輸入中匹配模式,返回true,否則返回false。
可以理解為:IsMatch方法,返回Matches方法返回的集合是否為空。