[英]Escape Special Character in Regex
有沒有辦法從字符串中轉義正則表達式中的特殊字符,例如[]()*
等?
基本上,我要求用戶輸入一個字符串,並且我希望能夠使用正則表達式在數據庫中進行搜索。 我遇到的一些問題too many)'s
或[xy] range in reverse order
,等等。
所以我想做的是編寫一個函數來替換用戶輸入。 例如,將(
替換為\\(
,將[
替換為\\[
正則表達式是否有內置函數可以這樣做? 如果我必須從頭開始編寫一個函數,有沒有一種方法可以輕松地計算所有字符,而不是一個一個地編寫替換語句?
我正在使用 Visual Studio 2010 在 C# 中編寫我的程序
為此,您可以使用 .NET 內置的Regex.Escape 。 復制自微軟的例子:
string pattern = Regex.Escape("[") + "(.*?)]";
string input = "The animal [what kind?] was visible [by whom?] from the window.";
MatchCollection matches = Regex.Matches(input, pattern);
int commentNumber = 0;
Console.WriteLine("{0} produces the following matches:", pattern);
foreach (Match match in matches)
Console.WriteLine(" {0}: {1}", ++commentNumber, match.Value);
// This example displays the following output:
// \[(.*?)] produces the following matches:
// 1: [what kind?]
// 2: [by whom?]
您可以將Regex.Escape用於用戶的輸入
string matches = "[]()*";
StringBuilder sMatches = new StringBuilder();
StringBuilder regexPattern = new StringBuilder();
for(int i=0; i<matches.Length; i++)
sMatches.Append(Regex.Escape(matches[i].ToString()));
regexPattern.AppendFormat("[{0}]+", sMatches.ToString());
Regex regex = new Regex(regexPattern.ToString());
foreach(var m in regex.Matches("ADBSDFS[]()*asdfad"))
Console.WriteLine("Found: " + m.Value);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.