如何在C#中替换部分字符串?

Tsu*_*ury 4 c# regex

假设我有以下字符串:

string str = "<tag>text</tag>";
Run Code Online (Sandbox Code Playgroud)

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

"<newTag>text</newTag>"
Run Code Online (Sandbox Code Playgroud)

最好的方法是什么?

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

Geo*_*off 22

为什么在你能做的时候使用正则表达式:

string newstr = str.Replace("tag", "newtag");
Run Code Online (Sandbox Code Playgroud)

要么

string newstr = str.Replace("<tag>","<newtag>").Replace("</tag>","</newtag>");
Run Code Online (Sandbox Code Playgroud)

编辑@ RaYell的评论

  • 或者如果您担心`tag`也可以是文本的一部分,您可以执行`str.Replace("<tag>","<newTag>").替换("</ tag>","</ newTag >");` (3认同)