我正在尝试从图像的srcset中提取单独的网址。
这是用于提取和下载该行中存在的所有文件。 我对它进行硬编码,因为行有时会有所不同。
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
答案 0 :(得分:1)
在这里,我们将在一个简单的char类中的表达式中添加一个量词,例如:
[^\s]{4,}
以获取所需的URL。
# 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可视化正则表达式: