Reputation: 739
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:
"<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...
Upvotes: 5
Views: 30993
Reputation: 1542
var input = "<tag>text</tag>";
var result = Regex.Replace(input, "(</?).*?(>)", "$1newtag$2");
Upvotes: -1
Reputation: 27313
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.
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));
}
Upvotes: 0
Reputation: 1038780
string str = "<tag>text</tag>";
string newValue = new XElement("newTag", XElement.Parse(str).Value).ToString();
Upvotes: 0
Reputation: 9340
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
Upvotes: 26
Reputation: 21720
To make it optional, simply add a "?" AFTER THE "/", LIKE THIS:
<[/?]*tag>
Upvotes: 3