[英]How to extract image name from string using python regexp?
有这样的文字:
body = """Some junk texts here.
<img src="/images/15244/somerandomname.jpg" class="news-img">
More texts here"""
我想知道如何使用python regexp提取somerandomname.jpg
?
我想到的是:
import re
regex = re.findall('/images/(\d+)/(\w+).jpg', body)
但是它确实返回一个空列表。
如果在模式中未定义捕获组( (...)
),则re.findall
返回整个匹配项;如果定义了捕获组,则re.findall
返回捕获的组。 由于您已经捕获了组,因此将进行后者。
删除捕获组以获取整个匹配项:
regex = re.findall('/images/\d+/\w+.jpg', body)
演示: https : //ideone.com/n1f9R8
您可以使用
regex = re.findall('/images/(\d+)/([^"]+)', body)
image_src = regex[0][1]
选中此表达式,它也适用于所有其他扩展名,例如jpg,png,ttf等...
re.findall('/ images / \\ d + /(\\ w +。\\ w {3,4})',body)
输出:['somerandomname.jpg']
您的代码有效,并且由于您只想捕获名称,因此它将起作用。
import re
body = """Some junk texts here.
<img src="/images/15244/somerandomname.jpg" class="news-img">
More texts here"""
regex = re.findall(r'/images/\d+/(\w+.jpg)', body)
print regex
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.