【问题标题】:How to replace http://locallhost with ~/ in html string如何在 html 字符串中将 http://localhost 替换为 ~/
【发布时间】:2019-08-22 20:01:39
【问题描述】:

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

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>

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

请帮忙。

【问题讨论】:

    标签: c# html asp.net regex


    【解决方案1】:

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

    http.*?/Images
    

    More information on greedy and lazy quantifiers on MSDN

    This Regex on Regex Storm

    但请注意,您的正则表达式也会匹配其中包含 /Images 的其他路径,例如:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-03-13
      • 2021-06-01
      • 1970-01-01
      • 2020-03-29
      • 1970-01-01
      • 2022-08-03
      • 2021-09-08
      相关资源
      最近更新 更多