Tsury
Tsury

Reputation: 739

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:

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

Answers (5)

MatteS
MatteS

Reputation: 1542

var input = "<tag>text</tag>";
var result = Regex.Replace(input, "(</?).*?(>)", "$1newtag$2");

Upvotes: -1

Jan Jongboom
Jan Jongboom

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

Darin Dimitrov
Darin Dimitrov

Reputation: 1038780

string str = "<tag>text</tag>";
string newValue = new XElement("newTag", XElement.Parse(str).Value).ToString();

Upvotes: 0

Geoff
Geoff

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

Marcos Placona
Marcos Placona

Reputation: 21720

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

<[/?]*tag>

Upvotes: 3

Related Questions