【问题标题】:How do I replace part of a string in C#?如何在 C# 中替换部分字符串?
【发布时间】:2010-03-26 11:06:25
【问题描述】:

假设我有以下字符串:

string str = "<tag>text</tag>";

我想将 'tag' 更改为 'newTag' 所以结果是:

"<newTag>text</newTag>"

最好的方法是什么?

我尝试搜索 [/]*tag> 但后来我不知道如何在结果中保留可选的 [/]...

【问题讨论】:

    标签: c# regex


    【解决方案1】:

    如果可以,为什么要使用正则表达式:

    string newstr = str.Replace("tag", "newtag");
    

    string newstr = str.Replace("<tag>","<newtag>").Replace("</tag>","</newtag>");
    

    编辑@RaYell 的评论

    【讨论】:

    • 或者如果您担心tag 也可能是文本的一部分,您可以这样做str.Replace("&lt;tag&gt;", "&lt;newTag&gt;").Replace("&lt;/tag&gt;", "&lt;/newTag&gt;");
    • 因为这适用于给定的示例,但在实践中效果不佳,您可以使用 这里是单词标签 。只是执行 string.Replace 调用有一个副作用。
    • 你可以做str.Replace("tag&gt;", "newTag&gt;");,这是一次通过,解决了“标签”在字符串中的其他地方的问题。
    【解决方案2】:

    要使其成为可选,只需添加一个“?”在“/”之后,像这样:

    <[/?]*tag>
    

    【讨论】:

      【解决方案3】:
      string str = "<tag>text</tag>";
      string newValue = new XElement("newTag", XElement.Parse(str).Value).ToString();
      

      【讨论】:

        【解决方案4】:

        您最基本的正则表达式可能是这样的:

        // find '<', find an optional '/', take all chars until the next '>' and call it
        //   tagname, then take '>'.
        <(/?)(?<tagname>[^>]*)>
        

        如果你需要匹配每个标签。


        或使用积极的前瞻,例如:

        <(/?)(?=(tag|othertag))(?<tagname>[^>]*)>
        

        如果你只想要tagothertag 标签。


        然后遍历所有匹配项:

        string str = "<tag>hoi</tag><tag>second</tag><sometag>otherone</sometag>";
        
        Regex matchTag = new Regex("<(/?)(?<tagname>[^>]*)>");
        foreach (Match m in matchTag.Matches(str))
        {
            string tagname = m.Groups["tagname"].Value;
            str = str.Replace(m.Value, m.Value.Replace(tagname, "new" + tagname));
        }
        

        【讨论】:

          【解决方案5】:
          var input = "<tag>text</tag>";
          var result = Regex.Replace(input, "(</?).*?(>)", "$1newtag$2");
          

          【讨论】:

          • 警告!这将替换任何标签,而不仅仅是“标签”。如果你有&lt;tag&gt;text&lt;/tag&gt;&lt;other&gt;text2&lt;/other&gt;,你最终会得到&lt;newtag&gt;text&lt;/newtag&gt;&lt;newtag&gt;text2&lt;/newtag&gt;
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-01-28
          • 2015-04-05
          • 2016-02-16
          • 2020-03-04
          • 2018-05-18
          相关资源
          最近更新 更多