替换为模式匹配

时间:2012-01-10 10:17:22

标签: c# pattern-matching

如何使用String.Replace函数来使用模式?

我想做什么:

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

#'任意数量的字符串#'可以是任何字符串。

4 个答案:

答案 0 :(得分:9)

使用正则表达式:

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

答案 1 :(得分:1)

也可以这样做吗?:

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

答案 2 :(得分:0)

您应该使用Regex这就是它存在的原因。 Regex

答案 3 :(得分:0)

使用Regex参考:

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);
相关问题