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

5

假设我有以下字符串:

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

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

"<newTag>text</newTag>"

最佳的方法是什么?

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

5个回答

26

当你可以这样做时,为什么要使用正则表达式:

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

根据 @RaYell 的评论进行了编辑


3
如果您担心tag可能也是文本的一部分,您可以使用str.Replace("<tag>", "<newTag>").Replace("</tag>", "</newTag>")来替换。请注意,该操作会将所有匹配项替换为<newTag></newTag> - RaYell
因为这在给定的示例中有效,但在实践中并不是很好,因为你可能会有<SomeOtherElement>这里是单词标签</SomeOtherElement>。仅执行string.Replace调用会产生副作用。 - itsmatt
你可以使用 str.Replace("tag>", "newTag>"); 进行一次替换,解决“tag”在字符串中的其他位置的问题。 - ChrisF

3
为了使其是可选的,只需在“/”之后添加一个“?”,像这样:
<[/?]*tag>

0
string str = "<tag>text</tag>";
string newValue = new XElement("newTag", XElement.Parse(str).Value).ToString();

0

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

// 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));
}

-1
var input = "<tag>text</tag>";
var result = Regex.Replace(input, "(</?).*?(>)", "$1newtag$2");

1
警告!这会替换任何标签,而不仅仅是“tag”。如果你有<tag>text</tag><other>text2</other>,你最终会得到<newtag>text</newtag><newtag>text2</newtag> - Andrew

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接