我寫這篇文章我知道有兩個部分對於這個問題,但是我想我只有真正停留在第一部分,因此第二僅供方面:從for循環生成的url列表中查找內容中的特定url需要什麼正則表達式?
A部分:
我需要搜索(其中每個值是一個網址)通過一個for循環返回的每個值中的內容如下:
href="/dir/Sub_Dir/dir/163472311232-text-text-text-text/page-n"
其中:
- 的標號
163472311232
可以是任何長度(即,它可以是5478
) -text-text-text-text
可以是任意數量的不同的詞- 其中
page-n
可以是來自page-2
直至任何數量 - 其中匹配是不返回不止一次,即只返回唯一匹配,因此只返回以下之一:
href="/dir/Sub_Dir/dir/5422-la-la/page-4
href="/dir/Sub_Dir/dir/5422-la-la/page-4
部分B:
所以邏輯是這樣的:
list_of_urls = original_list
for url in list_of_urls:
headers = {'User-Agent' : 'Mozilla 5.0'}
request = urllib2.Request(url, None, headers)
url_for_re = urllib2.urlopen(request).read()
another_url = re.findall(r'href="(/dir/Sub_dir\/dir/[^"/]*)"', url_for_re, re.I)
file.write(url)
file.write('\n')
file.write(another_url)
file.write('\n')
對此我希望給我的輸出類似於:
a.html
a/page-2.html
a/page-3.html
a/page-4.html
b.html
b/page-2.html
b/page-3.html
b/page-4.html
所以我的問題是(屁股在部分B的邏輯是好的):
什麼是要求的正則表達式模式用於部分?
我是新手到Python和正則表達式因此這將一定程度上限制了關於我的理解相對複雜的正則表達式的建議等
更新:
建議之後,我試圖測試以下的正則表達式這沒有產生任何結果:
import re
content = 'href="/dir/Sub_Dir/dir/5648342378-text-texttttt-texty-text-text/page-2"'
matches = re.findall(r'href="/dir/Sub_Dir/dir/[0-9]+-[a-zA-Z]+-[a-zA-Z]+-[a-zA-Z]+-[a-zA-Z]+/page-([2-9]|[1-9][0-9]+)"', content, re.I)
prefix = 'http://www.test.com'
for match in matches:
i = prefix + match + '\n'
print i
解決方案:
我認爲這是將工作的正則表達式:
matches = re.findall(r'href="(/dir/Sub_Dir/dir/[^"/]*/page-[2-9])"', content, re.I)
歡迎來到SO!在你的正則表達式的末尾有一個錯誤; 'page - ([2-9])|([1-9] [0-9] +)'應該是'page - ([2-9] | [1-9] [0-9] +)' 。當你使用這個站點出色的[代碼格式](http://stackoverflow.com/editing-help#code)功能時,這樣的錯誤更容易被發現。 ;) – 2013-05-01 05:28:54
我試圖測試這個正則表達式,但無法從中產生任何匹配。測試代碼被添加到原始文章。 – user1063287 2013-05-01 08:23:51
更新:我想我想出了一個解決方案,添加到原始文章。 – user1063287 2013-05-01 08:58:53