2016-01-19 627 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」之前和之後添加範圍「[]」。