How do I replace part of a string in C#?

前端 未结 5 784
旧时难觅i
旧时难觅i 2020-12-10 20:40

Supposed I have the following string:

string str = \"text\";

And I would like to change \'tag\' to \'newTag\' so the

相关标签:
5条回答
  • 2020-12-10 20:52
    string str = "<tag>text</tag>";
    string newValue = new XElement("newTag", XElement.Parse(str).Value).ToString();
    
    0 讨论(0)
  • 2020-12-10 20:55

    To make it optional, simply add a "?" AFTER THE "/", LIKE THIS:

    <[/?]*tag>
    
    0 讨论(0)
  • 2020-12-10 20:57
    var input = "<tag>text</tag>";
    var result = Regex.Replace(input, "(</?).*?(>)", "$1newtag$2");
    
    0 讨论(0)
  • 2020-12-10 21:05

    Why use regex when you can do:

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

    or

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

    Edited to @RaYell's comment

    0 讨论(0)
  • 2020-12-10 21:09

    Your most basic regex could read something like:

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

    If you need to match every tag.


    Or use positive lookahead like:

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

    if you only want tag and othertag tags.


    Then iterate through all the matches:

    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));
    }
    
    0 讨论(0)
提交回复
热议问题