2012-05-31 49 views
2

我使用Python中的正則表達式從文本中提取部分URL。我正在尋找的URL來自一組有限的模式,所以感覺就像我應該能夠在正則表達式中處理它們一樣。我試圖提取的是文件名的第一部分(「some.file.name」,位於以下的所有示例中),其中可以包含點,字母和數字。可選文件擴展名的正則表達式匹配

這些都是形式各種各樣的URL可以採取:

http://www.example.com/some.file.name.html 
http://www.example.com/some.file.name_foo.html 
http://www.example.com/some.file.name(123).html 
http://www.example.com/some.file.name_foo(123).html 
http://www.example.com/some.file.name 
http://www.example.com/some.file.name_foo 
http://www.example.com/some.file.name(123) 
http://www.example.com/some.file.name_foo(123) 

我覺得我非常有這個正則表達式:

http://www\.example\.com/([a-zA-Z0-9\.]+)(_[a-z]+)?(\(\d+\))?(\.html)? 

但它包括在名「.html」當URL與列表中的第一個一樣時的匹配。有沒有什麼方法可以阻止這種情況,或者它是正則表達式的一個基本限制嗎?

我很高興刪除代碼中的擴展名,因爲它始終是相同的,並且永遠不會作爲文件名的一部分有效,但作爲正則表達式匹配的一部分,它會更乾淨。

編輯:

我要強調的是,這些網址文字的機構。我無法保證他們之前或之後是否有角色,或者這些角色可能是什麼。我認爲假設他們不會是數字,字母,下劃線或點是安全的。

回答

2

正則表達式匹配貪婪默認。

試試這個正則表達式:

^http://www\.example\.com/([a-zA-Z0-9\.]+?)(_[a-z]+)?(\(\d+\))?(\.html)?$ 

注意額外的?添加到沒有捕捉到.html在第一部分。它使得第一組捕獲儘可能少匹配,而不是儘可能匹配。如果沒有?.html將包含在第一組中,因爲其他組是可選的,並且貪婪匹配嘗試儘可能「儘早」匹配。

P.S.還請注意,我使用^$來錨定正則表達式,以始終匹配整行。

+0

不幸的是,因爲文件之後的所有組name是可選的,使用'?'這裏只會給我一個文件名的第一個字母,因爲沒有什麼可以在URL的末尾「拉」正則表達式。 – alnorth29

+0

我的下一個想法是使用一個字邊界('\ b ')將正則表達式拉到URL的末尾,當然這不起作用,因爲'.'被當作字邊界。 – alnorth29

+0

這就是爲什麼我也添加了'$'符號的原因。 ? 在某些語言中,「matchin g「意味着」^「和」$「,而不是」開放式「的」搜索「。但我更喜歡用'^'和'$'顯式的方式。 但我沒有測試第一個問號是否足以使可選組更強。但它應該是「貪婪可選」? –

0

可以指定.html擴展爲非捕獲組:

http://www\.example\.com/([a-zA-Z0-9\.]+)(_[a-z]+)?(\(\d+\))?(?=(\.html)?) 
+0

不幸的是,這不是問題。我的問題是,「。html「被包含在第一組中,而不是它被捕獲到它自己的組中。 – alnorth29

+0

好吧,請嘗試後綴組:然後:(?=(\。html)?)在結尾而不是?: –

+0

我更新了我的回答 –

0

聽起來你不關心文件擴展名。你只是想提取文件名。

試試這個:

http://www\.example\.com/([\w]+.[\w]+.[\w()]+) 

在PHP中,我用preg_match_all($正則表達式,$海峽,$匹配),它返回這樣的事情。

Array 
(
    [0] => Array 
     (
      [0] => http://www.example.com/some.file.name 
      [1] => http://www.example.com/some.file.name_foo 
      [2] => http://www.example.com/some.file.name(123) 
      [3] => http://www.example.com/some.file.name_foo(123) 
      [4] => http://www.example.com/some.file.name 
      [5] => http://www.example.com/some.file.name_foo 
      [6] => http://www.example.com/some.file.name(123) 
      [7] => http://www.example.com/some.file.name_foo(123) 
     ) 

    [1] => Array 
     (
      [0] => some.file.name 
      [1] => some.file.name_foo 
      [2] => some.file.name(123) 
      [3] => some.file.name_foo(123) 
      [4] => some.file.name 
      [5] => some.file.name_foo 
      [6] => some.file.name(123) 
      [7] => some.file.name_foo(123) 
     ) 

) 

希望它有幫助!

相關問題