1

for example:

string str = $@"<html> < head > </ head > < body > <start> < h1 > Header 1 </ h1 > < p > A worker can be of 3 different types.</ p > <end> < p ></ p > </ body > </ html > "
string replacement = "hello world";
string newString = $@"<html> < head > </ head > < body > <start> < h1 > Header 1 </ h1 > < p > hello world</ p > <end> < p ></ p > </ body > </ html > "

So I have a <start> and <end> sign to know which part of the text should be replaced. How I can get the newString by regex.

1 Answer 1

4

Using Regex.Replace you set the pattern from the first <r> to the second, including all that is in between. Then you specify what to replace with.

var result = Regex.Replace(str, "<start>.*?<end>", $"<start> {replacement} <end>");

If prior to C# 6.0 string interpolation then:

var result = Regex.Replace(str, "<start>.*?<end>", string.Format("<start> {0} <end>",replacement));

With latest string from comments:

string str = $@"<html> < head > </ head > < body > <start> < h1 > Header 1 </ h1 > < p > A worker can be of 3 different types.</ p > <end> < p ></ p > </ body > </ html > ";
string replacement = "hello world";

var result = Regex.Replace(str, "<start>.*?<end>", $"<start> {replacement} <end>");
Sign up to request clarification or add additional context in comments.

13 Comments

This is too simple for regex. Use String.Replace() method which is more efficient.
@DoniyorNiyozov - what does it mean "didn't help"? It works for me..What C# are you using? if under c# 6.0 see update
You've used the lazy evaluator (?), which, combined with the optional many *, will match 0 characters. You want .*
@IsaacvanBakel - It works fine with the ? :) - It is for the case where he has more <r> in his string later on. Then I want the minimal match. Tested it
Gilad Green : The posting doesn't say 'between'. You are assuming something. I assumed that the person just wanted <r> replaced.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.