Wittinunt Khansuwan
Wittinunt Khansuwan

Reputation: 35

How to replace http://locallhost with ~/ in html string

I want to replace every "http://localhost:59455/" before "Images/TestFiles/(file name)" form my C# code below.

string tags = @"<p><img class='img - fluid' src='http://localhost:59455/Images/TestFiles/1.JPG'></p><p><br></p><p><img class='img-fluid' src='http://localhost:59455/Images/TestFiles/2.JPG'></p>";
string final = Regex.Replace(tags, "http.*/Images", "~/Images");

But it always give me wrong result like below:

<p><img class='img - fluid' src='~/Images/TestFiles/2.JPG'></p>

While I expected the result like:

<p><img class='img - fluid' src='~/Images/TestFiles/1.JPG'></p><p><br></p><p><img class='img-fluid' src='~/Images/TestFiles/2.JPG'></p>

You can see, it did replace only one.

Please help.

Upvotes: 0

Views: 694

Answers (1)

Manfred Radlwimmer
Manfred Radlwimmer

Reputation: 13394

The * is greedy and matches everything from the first http to the last /Images. Add a ? to make it lazy:

http.*?/Images

More information on greedy and lazy quantifiers on MSDN

This Regex on Regex Storm

Be careful though, your regex will also match other paths that have /Images in them, like these for example:

http://localhost:59455/Whatever/Images
http://localhost:59455/ImagesButDifferent

So you might want to make it more restrictive.

Upvotes: 1

Related Questions