假设我有以下字符串:
string str = "<tag>text</tag>";
我想将'tag'更改为'newTag',这样结果就是:
"<newTag>text</newTag>"
最佳的方法是什么?
我尝试搜索 <[/]*tag>,但我不知道如何在结果中保留可选的 [/]...
当你可以这样做时,为什么要使用正则表达式:
string newstr = str.Replace("tag", "newtag");
或者string newstr = str.Replace("<tag>","<newtag>").Replace("</tag>","</newtag>");
根据 @RaYell 的评论进行了编辑
<[/?]*tag>
string str = "<tag>text</tag>";
string newValue = new XElement("newTag", XElement.Parse(str).Value).ToString();
你最基本的正则表达式可能是这样的:
// 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));
}
var input = "<tag>text</tag>";
var result = Regex.Replace(input, "(</?).*?(>)", "$1newtag$2");
<tag>text</tag><other>text2</other>
,你最终会得到<newtag>text</newtag><newtag>text2</newtag>
。 - Andrew
tag
可能也是文本的一部分,您可以使用str.Replace("<tag>", "<newTag>").Replace("</tag>", "</newTag>")
来替换。请注意,该操作会将所有匹配项替换为<newTag>
和</newTag>
。 - RaYellstr.Replace("tag>", "newTag>");
进行一次替换,解决“tag”在字符串中的其他位置的问题。 - ChrisF