代码之家  ›  专栏  ›  技术社区  ›  Tsury

如何替换C中字符串的一部分?

  •  3
  • Tsury  · 技术社区  · 14 年前

    假设我有以下字符串:

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

    我想把“tag”改为“newtag”,结果是:

    "<newTag>text</newTag>"
    

    最好的方法是什么?

    我试图搜索<[/]*标记>,但我不知道如何在结果中保留可选的[/]…

    5 回复  |  直到 14 年前
        1
  •  20
  •   Geoff    14 年前

    为什么可以使用regex:

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

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

    编辑为@rayell的评论

        2
  •  3
  •   Marcos Placona    14 年前

    要使其成为可选的,只需添加“?”在“/”之后,如下所示:

    <[/?]*tag>
    
        3
  •  0
  •   Darin Dimitrov    14 年前
    string str = "<tag>text</tag>";
    string newValue = new XElement("newTag", XElement.Parse(str).Value).ToString();
    
        4
  •  0
  •   Jan Jongboom    14 年前

    最基本的regex可以读取如下内容:

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

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


    或者使用积极的前瞻性,比如:

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

    如果你只想 tag othertag 标签。


    然后迭代所有匹配项:

    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
  •  0
  •   MatteS    14 年前
    var input = "<tag>text</tag>";
    var result = Regex.Replace(input, "(</?).*?(>)", "$1newtag$2");