淺析C#正則表達式
C#正則表達式選項
可以使用影響匹配行為的選項修改C#正則表達式模式??梢酝ㄟ^兩種基本方法設置C#正則表達式選項:其一是可以在 Regex(pattern, options) 構造函數中的 options 參數中指定,其中 options 是 RegexOptions 枚舉值的按位"或"組合;其二是使用內聯 (?imnsx-imnsx:) 分組構造或 (?imnsx-imnsx) 其他構造在正則表達式模式內設置它們。
在內聯選項構造中,一個選項或一組選項前面的減號 (-) 用于關閉這些選項。例如,內聯構造 (?ix-ms) 將打開 IgnoreCase 和 IgnorePatternWhiteSpace 選項而關閉 Multiline 和 Singleline 選項。
表2:RegexOptions 枚舉的成員以及等效的內聯選項字符
例如,Find_po在字開頭處查找以"po"開頭的字符串:
- staticvoidFind_po()
- {
- stringtext=@"IcannotfindmypositioninBeijing";
- stringpattern=@"\bpo\S*ion\b";
- MatchCollectionmatches=Regex.Matches(text,pattern,RegexOptions.IgnoreCase
- |RegexOptions.IgnorePatternWhitespace|RegexOptions.ExplicitCapture);
- WriteMatches(text,matches);
- }
這段代碼還使用了名稱空間RegularExpressions:
- using System;
- using System.Text.RegularExpressions;
以上介紹C#正則表達式
【編輯推薦】