2016-01-19 49 views
0

使用grep /正则表达式,我试图将img标签拉出文件。我只希望在源代码中包含'photobucket'的img标签,并且我不想要不包含photobucket的img标签。只有grep img标签包含关键字,但不是img标签不包含?

旺旺:

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

不想:

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

我曾尝试:

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

这没有工作,因为它在拉第二个例子“做不想要“,因为有一个”photobucket“,然后是一个右括号。我怎么才能检查'光桶',直到第一个左括号,如果没有光桶,请忽略它并继续前进?

'photobucket'可能位于字符串内的不同位置。

+0

尝试 Aferrercrafter

+0

我确实需要那里的通配符,因为并非所有的img标签都是一致的“img src =”,有些包含类,有些包含alt文本,有些则不包含。 –

+0

true..let我现在做点什么 – Aferrercrafter

回答

1
grep -o '<img[^>]*src="[^"]*photobucket[^>]*>' infile 

-o只返回匹配。分手:

<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选项(Perl的正则表达式)。

+0

确实[^>] *算作通配符,基本上说0除了右括号外还有其他的东西? –

+0

准确地说:它是一个字符类(或“括号表达式”)'[]',第一个字符是一个'^',否定类。当你知道分隔符时,这是一种非贪婪的匹配方式。 –

+0

我不知道你只能放一个否定字符,并让它匹配其他所有字符。 –

0

尝试以下操作:

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

这样的正则表达式不能得到过去 '>'

0

这种模式尝试:

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

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