如何使用python regexp从字符串中提取图像名称?

时间:2017-06-19 06:51:59

标签: python regex

有这样的文字:

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)

但确实会返回一个空列表。

4 个答案:

答案 0 :(得分:3)

如果模式中未定义捕获组(re.findall),则

(...)将返回整个匹配项,如果已定义,则返回捕获的组。由于你有捕获组,后者发生。

删除捕获组以获得整个匹配:

regex = re.findall('/images/\d+/\w+.jpg', body)

演示:https://ideone.com/n1f9R8

答案 1 :(得分:1)

你可以使用

regex = re.findall('/images/(\d+)/([^"]+)', body)
image_src = regex[0][1]

答案 2 :(得分:1)

您只需要将图像名称部分分组。

检查此表达式,它也适用于所有其他扩展程序,即jpg,png,ttf etc...

  

re.findall('/ images / \ d + /(\ w +。\ w {3,4})',正文)
  输出:['somerandomname.jpg']

答案 3 :(得分:0)

您的代码有效,因为您只想捕获名称,这将起作用。

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