2013-08-16 141 views
-1

我想在SQL分組條件,以取代領域的鑄造版的領域:正則表達式替換SQL分組

例如:

input: sum(count(andrei) + count(2) + sum(count3) 

ouptput: sum(count(cast(andrei as int)) + count(cast(2 as int)) + sum(cast(count3 as int)) 

我的想法是要找到不包含文字使用以下模式的「(」或「)」:

Match m = Regex.Match(input, "\\([^\\(\\)]+\\)"); 

然後用鑄造版本替換它們。

我不知道如何執行替換。

+1

你需要一個Regex.Replace()。我希望這篇文章能夠幫助你http://msdn.microsoft.com/ru-ru/library/xwewhkd1.aspx – MikkaRin

+1

我強烈建議你在定義表達式時使用一個文字字符串。 RegEx已經有足夠的斜槓。 – Logarr

回答

1

您可以使用以下模式和替換字符串。

模式:(?<=\()([^()]+)(?=\))

  • (?<=\():尋找隱藏匹配(但不消耗)左括號
  • ([^()]+):帶負字符類編號的捕獲組除了該開口,以匹配任何東西,關閉括號。當他們出現在角色類中時,不需要逃避他們。
  • (?=\)):先行檢測右括號

替換字符串:cast($1 as int)其中$1指的是第一個編號捕獲組

string input = "sum(count(andrei)) + count(2) + sum(count3)"; 
string pattern = @"(?<=\()([^()]+)(?=\))"; 
string replacement = "cast($1 as int)"; 
string result = Regex.Replace(input, pattern, replacement); 
Console.WriteLine(result);