2011-05-04 33 views
1

由於redbubble.com缺乏API,我使用ATOM feed來竊取有關用戶圖片的信息。正則表達式來獲取包含關鍵字的URL

這是XML的樣子:

<entry> 
    <id>ID</id> 
    <published>Date Published</published> 
    <updated>Date Updated</updated> 
    <link type="text/html" rel="alternate" href="http://www.redbubble.com/link/to/post"/> 
    <title>Title</title> 
    <content type="html"> 
    Blah blah blah stuff about the image.. 
    &lt;a href="http://www.redbubble.com/products/configure/config-id"&gt;&lt;img src="http://ih1.redbubble.net/path-to-image" alt="" /&gt; 
    </content> 
    <author> 
    <name>Author Name</name> 
    <uri>http://www.redbubble.com/people/author-user-name</uri> 
    </author> 
    <link type="image/jpeg" rel="enclosure" href="http://ih0.redbubble.net/path-to-the-original-image"/> 
    <category term="1"/> 
    <category term="2"/> 
</entry> 

基本上使用正則表達式...我將如何去獲得在內容標籤的鏈接裏面href財產?我們知道肯定

的一件事是,它會永遠路徑中有配置即http://somesite.com/**configure**/id

所以基本上我只需要找到與配置URL,並抓住了整個事情...

+0

什麼編程語言? – 2011-05-04 13:27:33

回答

1

感謝您的真棒答案,但我的同事爲我解決了它!

這就是我最終使用:

/http:\/\/([^"\/]*\/)*configure\/([^"]*)/ 

(Ruby的正則表達式的方式)

1

不管你正在使用的編程語言,不要試圖用正則表達式來解析整個事物。首先使用XML解析器來提取href="..."。然後,當然,使用正則表達式來確保URL包含configure

正如@KARASZI所評論的,XPath是另一種好方法。

+1

甚至可以更好地使用XPath。 – 2011-05-04 13:30:18

+0

如果性能確實是問題,則只能先解析XML。否則,只需要使用正則表達式 - 代碼更簡單... – Elad 2011-05-04 13:33:26

2

以下正則表達式將根據您的要求提取href內容。它似乎適用於示例代碼。

href="(\w[^"]+/configure/\w[^"]+) 
+0

爲什麼不使用lookaheads/lookbehinds? – Ishpeck 2011-05-04 13:32:29

+0

@ishpeck - 我相信這可能是一個更有效的正則表達式搜索。 – Leons 2011-05-04 13:38:54

+0

'\ w'是不必要的 – stema 2011-05-04 13:47:23

1

如果你必須使用正則表達式試試這個:

href="(?=[^"]*configure)([^"]*) 

rubular.com

我使用的是向前看找到它是否包含配置。