【问题标题】:RegEx for matching URLs and failing non-URLs用于匹配 URL 和失败的非 URL 的正则表达式
【发布时间】:2019-05-31 03:33:26
【问题描述】:

我正在尝试从图像的 srcset 中提取分离的 url。

这用于提取和下载行中存在的所有文件。 我没有硬编码它,因为行有时会有所不同。

txt = "images/1x/1083bce6__color_272x92dp.png 1x, images/2x/b3716cd2_color_272x92dp.png 2x"

reg = re.compile(r"((?:[^\s,]+))(?:.*?,)?").finditer

for i in list(reg(txt)):
   print(i.group(1))


我希望结果是两个网址

images/1x/1083bce6__color_272x92dp.png
images/2x/b3716cd2_color_272x92dp.png

但我得到三个额外的存在

2x

【问题讨论】:

    标签: python regex string regex-negation regex-greedy


    【解决方案1】:

    在这里,我们将在一个简单的 char 类中添加一个量词,例如:

    [^\s]{4,}
    

    获取我们想要的 URL。

    Demo

    测试

    # coding=utf8
    # the above tag defines encoding for this document and is for Python 2.x compatibility
    
    import re
    
    regex = r"[^\s]{4,}"
    
    test_str = "images/1x/1083bce6__color_272x92dp.png 1x, images/2x/b3716cd2_color_272x92dp.png 2x"
    
    matches = re.finditer(regex, test_str, re.MULTILINE)
    
    for matchNum, match in enumerate(matches, start=1):
        
        print ("Match {matchNum} was found at {start}-{end}: {match}".format(matchNum = matchNum, start = match.start(), end = match.end(), match = match.group()))
        
        for groupNum in range(0, len(match.groups())):
            groupNum = groupNum + 1
            
            print ("Group {groupNum} found at {start}-{end}: {group}".format(groupNum = groupNum, start = match.start(groupNum), end = match.end(groupNum), group = match.group(groupNum)))
    
    # Note: for Python 2.7 compatibility, use ur"" to prefix the regex and u"" to prefix the test string and substitution.
    

    正则表达式

    如果不需要此表达式,可以在 regex101.com 中修改/更改。

    正则表达式电路

    jex.im 可视化正则表达式:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多