[英]What are the things to watch out for with case insensitive regex replace?
我編寫了以下代碼以在C#中執行不區分大小寫的替換:
Regex.Replace(textBoxText,
Regex.Escape(findText),
replaceText,
RegexOptions.IgnoreCase);
只是想檢查一下,這是正確的方法,還是有更好的方法,以及我是否忽略了我應該更好地意識到的東西。
注意:請不要提供一些手工編寫的代碼,我使用了codeproject中的快速替換功能,該代碼在客戶端崩潰,並且我無法知道用戶使用了什么輸入。 因此,我更喜歡一些簡單但正確和可靠的方法。
您的代碼似乎還可以,但是請記住,當您進行不區分大小寫的匹配時,您將使用當前的語言環境或區域性。 最好添加所需的文化,或者讓用戶選擇它。 通常, CultureInvariant
是在任何語言環境中執行相同操作的良好通用選擇:
Regex.Replace(textBoxText,
Regex.Escape(findText),
replaceText,
RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
要使用其他語言環境,您需要做更多的工作:
// remember current
CultureInfo originalCulture = Thread.CurrentThread.CurrentCulture;
// set user-selected culture here (in place of "en-US")
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-US");
// do the regex
Regex.Replace(textBoxText,
Regex.Escape(findText),
replaceText,
RegexOptions.IgnoreCase);
// reset the original culture
Thread.CurrentThread.CurrentCulture = originalCulture;
請注意,您可以打開或關閉不區分大小寫。 這不是切換,這意味着:
// these three statements are equivalent and yield the same results:
Regex.Replace("tExT", "[a-z]", "", RegexOptions.IgnoreCase);
Regex.Replace("tExT", "(?i)[a-z]", "", RegexOptions.IgnoreCase);
Regex.Replace("tExT", "(?i)[a-z]", "");
// once IgnoreCase is used, this switches it off for the whole expression...
Regex.Replace("tExT", "(?-i)[a-z]", "", RegexOptions.IgnoreCase);
//...and this can switch it off for only a part of the expression:
Regex.Replace("tExT", "(?:(?-i)[a-z])", "", RegexOptions.IgnoreCase);
最后一個很有趣:在非捕獲括號后的(?:)
之間,大小寫轉換(?-i)
不再有效。 您可以在表達式中隨意使用它。 在不分組的情況下使用它可以使它們有效,直到下一個區分大小寫的開關或結束為止。
更新: 我錯誤地假設您無法進行區分大小寫的切換。 在編輯上面的文本時,請牢記這一點。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.