Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I replace part of a string in C#?

Tags:

c#

regex

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

like image 741
Tsury Avatar asked Mar 26 '10 11:03

Tsury


2 Answers

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

like image 95
Geoff Avatar answered Oct 04 '22 23:10

Geoff


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

<[/?]*tag>
like image 34
Marcos Placona Avatar answered Oct 05 '22 01:10

Marcos Placona