【问题标题】:Regex to modify specific URLs in large strings正则表达式修改大字符串中的特定 URL
【发布时间】:2009-08-26 15:07:11
【问题描述】:

我无法让我的正则表达式工作(大惊喜)

我正在尝试替换大量文本中的网址:

<img src="http://www.example.com/any/number/of/directories/picture.jpg" ...

<img src="http://www.example.com/any/number/of/directories/picture.gif" ...

与:

<img src="/LocalDirectory/images/picture.jpg" ...

我想保留图像的名称,并且我不能有任何虚假的帖子,因为原始文本将包含我想不理会的其他 URL。我只想修改图片,以便可以匹配 jpg|jpeg|gif|png 等或

我在 C# 中这样做。

【问题讨论】:

    标签: c# regex


    【解决方案1】:

    因为我已经有了这个方便,这应该获取 URL 本身:

    (?<=src=")[^"]+(?=")
    

    Regex Hero 中验证,此正则表达式使用正向后视和正向前瞻来获取 src="" 内的 url。

    我会看看能不能为你的任务想出一些更具体的东西......

    好的,这应该可以:

    (?<=src=")[^"]+(/[^/]+(\.jpg|\.gif))(?=")
    

    然后您可以使用以下替换值:

    /LocalDirectory/images$1
    

    或者这里是完整的 C# 代码:

    string strRegex = "(?<=src=\")[^\"]+(/[^/]+(\.jpg|\.gif))(?=\")";
    RegexOptions myRegexOptions = RegexOptions.None;
    Regex myRegex = new Regex(strRegex, myRegexOptions);
    string strTargetString = "<img src=\"http://www.example.com/any/number/of/directories/picture.jpg\" />" & vbCrLf & "<img src=\"http://www.example.com/any/number/of/directories/picture.gif\" />";
    string strReplace = "/LocalDirectory/images$1";
    
    return myRegex.Replace(strTargetString, strReplace);
    

    【讨论】:

    • 请注意,' 在 HTML 4.01 中对于包装属性值(而不是 ")是有效的,因此这不适用于所有页面。
    【解决方案2】:

    使用正则表达式匹配 URL 是非常困难的,如果不是不可能的话。除非您对文档中的 URL 包含的内容有一些额外的限制,在这种情况下,您可以牺牲正则表达式的灵活性以换取实用性。

    【讨论】:

    • 我想要的只是 url 的最后一位(即文件名)。文件名只能是jpg等,开头会有一个img src="http://。
    • 当 URL 包含在 HTML 文件的 href 中时会更容易一些。然后你就可以知道 URL 从哪里开始和停止了。
    • 那么你应该使用一些 HTML 抓取库来获取图像标签的 src 属性,然后在 URI 上使用正则表达式。尽量避免使用正则表达式来解析 HTML 本身。
    【解决方案3】:
    strTargetString = "img tags to check";
    string strRegex = "src=\"(.*)/(.*)\.(jpg|png|gif)\"";
    RegexOptions myRegexOptions = RegexOptions.Multiline | RegexOptions.IgnorePatternWhitespace;
    Regex myRegex = new Regex(strRegex, myRegexOptions);
    
    string strReplace = "src="\/LocalDirectory\/images\/$2\.$3"";
    
    return myRegex.Replace(strTargetString, strReplace);
    

    误读了问题。这将替换 jpg、png 和 gif 路径的第一部分并保留文件名。其他任何东西都会被忽略

    【讨论】:

    • 不用担心。他看起来比我的整洁
    【解决方案4】:

    希望这会有所帮助:

    var replace = "/localserver/some/directory/";
    var strs = new List<string>
    {
        "<img src=\"http://www.example.com/any/number/of/directories/picture.jpg\"",
        "<img src=\"http://www.example.com/any/number/of/directories/picture.gif\"" 
    };
    
    Regex r = new Regex("[^<img src=\"].*/");
    
    foreach (var s in strs)
    {
        Console.WriteLine("Replaced: {0}",r.Replace(s,replace));
    }
    

    输出:

    Replaced: <img src="/localserver/some/directory/picture.jpg"
    Replaced: <img src="/localserver/some/directory/picture.gif"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-04
      • 2015-12-13
      • 1970-01-01
      • 2018-09-14
      • 2011-01-12
      • 1970-01-01
      • 1970-01-01
      • 2014-11-10
      相关资源
      最近更新 更多