[英]Find multiple occurrences of different URLs in a big string, where each URL is between two specific substrings using Python
我有一個僅包含一個長字符串的文件,該字符串中嵌入了多個URL。 URL都是不同的,但始終包含在兩個特定的子字符串之間。 如何提取所有URL?
我的文件內容如下所示:
data-starred-src="www.example.com" data-non-starred-src asdf asdf ghgh data-starred-src="www.someurl.com" data-non-starred-src gjsltg ajshssl ahssfh data-starred-src="www.anotherurl.com" data-non-starred-src
我想提取表單中的URL
www.example.com
www.someurl.com
www.anotherurl.com
在示例中,此示例:
print re.findall(r'data-starred-src\s*=\s*"([^"]*)"', line)
得到:
['www.example.com', 'www.someurl.com', 'www.anotherurl.com']
應該這樣做:
(?<=\")([^"]+\.[^"]+\.[^"]+)(?=\")
工作正則表達式示例:
或另一個例子:
請嘗試以下操作:
import re
r1 = re.compile('(?:AAA ")([^"]*)(?:" BBB)')
s = 'AAA "www.example.com" BBB asdf asdf ghgh AAA "www.someurl.com" BBB gjsltg ajshssl ahssfh AAA "www.anotherurl.com" BBB'
res = r1.findall(s)
如果s
真的很長,您也可以考慮使用finditer()
。
更新后的內容看起來像這樣
r1 = re.compile('(?:data-starred-src=")([^"]*)(?:" data-non-starred-src)')
但是我只是用新的定界符替換了AAA和BBB,所以如果以前不起作用,則該代碼可能無法起作用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.