2010-03-16 273 views
0

替換字符串我有一個看起來像各種字符串:解析和使用正則表達式

$(gateway.jms.jndi.ic.url,0,tibjmsnaming, tcp)/topic/$(gateway.destination.prefix)$(gateway.StatusTopicName),$(gateway.jms.jndi.ic.username),$(gateway.jms.jndi.ic.password),abinding,tBinding 

我試圖想出一個辦法來提取$(...)切片和其他一些替代它們串。

在C#中是否有解析這些組並用另一個字符串替換一個接一個?

感謝

回答

5

這個正則表達式將捕獲這些部分:

\$\([^)]+\)

然後更換這樣的(這個例子改變每場比賽它的大寫形式 - 你可以添加任何自定義你想要的邏輯):

Regex.Replace(candidate, @"\$\([^)]+\)", delegate(Match m) { 
    return m.ToString().ToUpper(); 
}); 
+0

太棒了!如果我希望匹配結果將不包含'$'或'('')'字符,該怎麼辦? 謝謝 – 2010-03-16 16:19:55

0

我不太擅長delegate.s這裏是我想出了使用安德魯的正則表達式:

string test1 = @"$(gateway.jms.jndi.ic.url,0,tibjmsnaming, tcp)/topic/$(gateway.destination.prefix)$(gateway.StatusTopicName),$(gateway.jms.jndi.ic.username),$(gateway.jms.jndi.ic.password),abinding,tBinding"; 

      string regex1 = @"\$\([^)]+\)"; 

      var matches = Regex.Matches(test1, regex1); 

      Console.WriteLine(matches.Count); 
      foreach (Match match in matches) 
      { 
       test1 = test1.Replace(match.Value, "your String");     
      } 
      Console.WriteLine(test1); 
+0

你應該直接使用Regex.Replace代替你的foreach循環 – PierrOz 2010-03-16 15:52:19

+0

謝謝我明白了。 – DotNetWala 2010-03-16 16:06:02