[英]How do I replace part of a string in C#?
Supposed I have the following string:假设我有以下字符串:
string str = "<tag>text</tag>";
And I would like to change 'tag' to 'newTag' so the result would be:我想将 'tag' 更改为 'newTag' 所以结果是:
"<newTag>text</newTag>"
What is the best way to do it?最好的方法是什么?
I tried to search for <[/]*tag> but then I don't know how to keep the optional [/] in my result...我试图搜索 <[/]*tag> 但后来我不知道如何在我的结果中保留可选的 [/] ...
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编辑为@RaYell 的评论
To make it optional, simply add a "?"要使其可选,只需添加一个“?” AFTER THE "/", LIKE THIS:在“/”之后,像这样:
<[/?]*tag>
string str = "<tag>text</tag>";
string newValue = new XElement("newTag", XElement.Parse(str).Value).ToString();
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.如果你只想要tag
和othertag
标签。
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));
}
var input = "<tag>text</tag>";
var result = Regex.Replace(input, "(</?).*?(>)", "$1newtag$2");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.