只有包含关键字的grep img标签,但不包含不是img的标签?

时间:2016-01-19 16:53:20

标签: regex grep bbedit

使用grep / regex,我试图从文件中提取img标签。我只想要包含' photobucket'的img标签。在源代码中,我不希望img标签不包含photobucket。

想要:

<img src="/photobucket/img21.png">

不想要:

<img src="/imgs/test.jpg">
<img src="/imgs/thiswillgetpulledtoo.jpg"><p>We like photobucket</p>

我尝试过:

(<img.*?photobucket.*?>)

这不起作用,因为它推出了第二个例子,因为有一个&#39; photobucket&#39;然后是一个结束括号。我怎样才能检查&#39; photobucket&#39;直到第一个结束括号,如果没有包含photobucket,忽略它并继续前进?

&#39;的photobucket&#39;可能在字符串中的不同位置。

4 个答案:

答案 0 :(得分:2)

只需添加>符号的否定:

(<img[^>]*?photobucket.*?>)

https://regex101.com/r/tZ9lI9/2

答案 1 :(得分:1)

<img          # Start with <img
[^>]*         # Zero or more of "not >"
src="         # start of src attribute
[^"]*         # Zero or more or "not quotes"
photobucket   # Match photobucket
[^>]*         # Zero or more of "not >"
>             # Closing angle bracket

<img src="/imgs/test.jpg"> <img src="/imgs/thiswillgetpulledtoo.jpg"><p>We like photobucket</p> <img src="/photobucket/img21.png"> <img alt="photobucket" src="/something/img21.png"> <img alt="something" src="/photobucket/img21.png"> <img src="/photobucket/img21.png" alt="something"> <img src="/something/img21.png" alt="photobucket"> 仅返回匹配项。分手:

$ grep -o '<img[^>]*src="[^"]*photobucket[^>]*>' infile
<img src="/photobucket/img21.png">
<img alt="something" src="/photobucket/img21.png">
<img src="/photobucket/img21.png" alt="something">

输入文件

.*?

返回

-P

非贪婪的{{1}}仅适用于{{1}}选项(Perl正则表达式)。

答案 2 :(得分:0)

尝试以下方法:

<img[^>]*?photobucket[^>]*?>

这样正则表达式就无法超越&#39;&gt;&#39;

答案 3 :(得分:0)

尝试使用此模式:

<img.*src=\"[/a-zA-Z0-9_]+photobucket[/a-zA-Z0-9_]+\.\w+\".*>

我不确定名称文件夹所包含的字符,但您只需要在“photobucket”之前和之后添加“[]”范围。