簡體   English   中英

使用C#Regex的多個正則表達式選項

[英]Multiple regex options with C# Regex

假設我有這個:

Regex.Replace("aa cc bbbb","aa cc","",RegexOptions.IgnoreCase);

但我也需要忽略空格。 所以,我找到了一個選項IgnorePatternWhitespace ,但是如何將一些選項添加到一個regex.Replace?
就像是:

Regex.Replace("aa cc bbbb", "aa cc", "", 
    RegexOptions.IgnoreCase + RegexOptions.IgnorePatterWhitespace);

更新:
謝謝你的答案,但這個選項似乎不起作用:這是一個測試示例:

Regex.Replace("aa cc bbbb", "aacc", "", 
    RegexOptions.IgnoreCase | RegexOptions.IgnorePatterWhitespace);

使用按位OR( |

Regex.Replace("aa cc bbbb",
                "aa cc",
                "",
                RegexOptions.IgnoreCase | RegexOptions.IgnorePatterWhitespace); 
Regex.Replace("aa cc bbbb","aa cc","",RegexOptions.IgnoreCase | RegexOptions.IgnorePatterWhitespace);

使用| 運營商。

編輯:

你完全錯了。 RegexOption.IgnorePatterWhitespace忽略正則表達式中的空格,以便您可以執行以下操作:

string pattern = @"
^                # Beginning of The Line
\d+              # Match one to n number but at least one..
";

然而,你認為進入空白會將"aa cc bbbb"變成"aaccbbbb" ,這顯然是錯誤的。

根據MSDN

RegexOption枚舉值的按位OR組合。

所以只需使用OPT_A | OPT_B OPT_A | OPT_B

您可以擁有任意數量的RegexOptions,只需“或”與“|”。

例如...

RegexOptions.Compiled | RegexOptions.IgnoreCase

IgnorePatternWhitespace
消除模式中未轉義的空白區域並啟用標記為#的注釋。 但是,IgnorePatternWhitespace值不會 影響或消除字符類中的空格。

所以:

string result = Regex.Replace("aa cc bbbb","aa|cc","",RegexOptions.IgnoreCase).Trim();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM