Ave
Ave

Reputation: 4430

Can't replace text on string in C#

I have string like:

          Student 12:00AMLeoPan        Final points        
<!--<div class='icon displayOn' ><span onclick=';' title=''></span></div>-->0.5
      &nbsp;         2.00<!--<div class='icon'><spanonclick='' title=''></span></div>-->    

I want to replace string StartWith <!--<div to end </div>-->, and string &nbsp to "" values.

I tried with my code:

string finalResult = Regex.Replace(abc, "<!--<div" + ".*</div>-->&nbsp;", "")
                          .Replace("<!--<div" + ".*</div>-->", "")
                          .Replace("&nbsp;", "");`

But Regex.Replace can't replace.

How to remove this string? Thanks.

Updated 1:

Thanks, @Mark.

I tried with: .Replace("<!--<div" + ".*</div>-->", "").

And it remove all:

<!--<div class='icon displayOn' ><span onclick=';' title=''></span></div>-->0.5 &nbsp; 2.00<!--<div class='icon'><spanonclick='' title=''></span></div>-->.

Result only: Student 12:00AMLeoPan Final points.

You can see I have two have start with: <!--<div and end with: </div>-->.

But it replaces all. And want final result to show like:

Student 12:00AMLeoPan Final points 0.5 &nbsp; 2.00

Upvotes: 0

Views: 420

Answers (1)

Mark
Mark

Reputation: 8150

Regex.Replace returns a string, so your 2nd and 3rd Replace calls are actually calling String.Replace, which doesn't support regex. Don't chain the calls - call Regex.Replace explicitly each time, e.g.

string r1 = Regex.Replace(abc, "<!--<div.*?</div>-->&nbsp;", "");
string r2 = Regex.Replace(r1, "<!--<div.*?</div>-->", "");
string finalResult = Regex.Replace(r2, "&nbsp;", "");

Update: As mentioned by @WhoIsRich in a comment on the question, the regex was modified to be non-greedy.

Upvotes: 6

Related Questions