2012-01-10 235 views
1

如何使用String.Replace函數來使用模式?替換爲模式匹配

我想這樣做:

newTextBox = newTextBox.Replace("<Value> #'a string of any number of chars#' </Value>", 
           "<Value>" + textBoxName + "</Value>"); 

#「任意數目的字符#的字符串」可以是任何字符串。

+8

正則表達式? – CodeZombie 2012-01-10 10:18:56

回答

9

使用正則表達式:

newTextBox.Text = 
    Regex.Replace(
     newTextBox.Text, 
     @"<Value>[^\<]+</Value>", 
     "<Value>" + textBoxName.Text + "</Value>"); 
+0

我會添加一個簡短的正則表達式的解釋,並鏈接到作弊表http://www.mikesdotnetting.com/Article/46/CSharp-Regular-Expressions-Cheat-Sheet – ANeves 2012-01-10 10:25:52

0

您應該使用Regex,這就是爲什麼它的存在。 Regex

1

也可以做這樣的?:

 const string textBoxName = "textBoxName"; 
     var newTextBox = "<Value>{0}</Value>".Replace("{0}", textBoxName); 
+0

爲什麼使用'string.Replace(。 ..)'而不是'string.Format(字符串格式,...)'? – Nuffin 2012-01-10 10:56:44

+0

@Tobias:確實如此。如果我要演示哪些元素被替換爲{0},{1},{2}等,或者是否需要特定的格式(Int16或具有N個零/小數位的浮點數),String.Format會更好。 )。我猜如果OP使用佔位符如'#replaceabletext#'或{0}以外的其他東西,我給出的.Replace()示例會更合適。{N} – 2012-01-10 11:25:05

0

用正則表達式參考:

using System.Text.RegularExpressions; 

而且要替換字符:[0-9a-zA-Z_#' ]

newTextBox.Text = Regex.Replace(
    "<Value> #'a string of any number of chars#' </Value>", 
    @"<Value>[0-9a-zA-Z_#' ]*</Value>", 
    "<Value>" + textBoxName.Text + "</Value>", 
    RegexOptions.IgnoreCase);