tags:

views:

117

answers:

5

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...

+11  A: 

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

Geoff
or if you fear that `tag` can be also the part of the text you can do `str.Replace("<tag>", "<newTag>").Replace("</tag>", "</newTag>");`
RaYell
Because this works for the given example but not so well in practice where you could have <SomeOtherElement> here is the word tag </SomeOtherElement>. There is a side-effect of just doing the string.Replace call.
itsmatt
you could do `str.Replace("tag>", "newTag>");` which is one pass and solves the problem of "tag" being elsewhere in the string.
ChrisF
+3  A: 

To make it optional, simply add a "?" AFTER THE "/", LIKE THIS:

<[/?]*tag>
Marcos Placona
A: 
string str = "<tag>text</tag>";
string newValue = new XElement("newTag", XElement.Parse(str).Value).ToString();
Darin Dimitrov
A: 

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));
}
Jan Jongboom
A: 
var input = "<tag>text</tag>";
var result = Regex.Replace(input, "(</?).*?(>)", "$1newtag$2");
MatteS