如何在 html 字符串中用 ~/ 替换 http://locallhost



我想在下面形成我的 C# 代码之前替换每个"http://localhost:59455/" "Images/TestFiles/(file name)"

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

但它总是给我错误的结果,如下所示:

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

虽然我期望的结果是这样的:

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

你可以看到,它只替换了一个。

请帮忙。

*贪婪,会匹配从第一个http到最后一个/Images的所有内容。添加一个?使其延迟

http.*?/Images

有关 MSDN 上的贪婪和惰性量词的详细信息

则表达式风暴上的这个正则表达式

但要小心,您的正则表达式也会匹配其他包含/Images的路径,例如:

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

因此,您可能希望使其更具限制性。

最新更新