【发布时间】:2010-03-26 11:06:25
【问题描述】:
假设我有以下字符串:
string str = "<tag>text</tag>";
我想将 'tag' 更改为 'newTag' 所以结果是:
"<newTag>text</newTag>"
最好的方法是什么?
我尝试搜索 [/]*tag> 但后来我不知道如何在结果中保留可选的 [/]...
【问题讨论】:
假设我有以下字符串:
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 也可能是文本的一部分,您可以这样做str.Replace("<tag>", "<newTag>").Replace("</tag>", "</newTag>");
str.Replace("tag>", "newTag>");,这是一次通过,解决了“标签”在字符串中的其他地方的问题。
要使其成为可选,只需添加一个“?”在“/”之后,像这样:
<[/?]*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>。