python正則怎么提取域名
問(wèn)題描述
<script type='application/ld+json'>{ '@context': 'http://schema.org', '@type': 'SaleEvent', 'name': '10% Off First Orders', 'url': 'https://www.myvouchercodes.co.uk/coggles', 'image': 'https://mvp.tribesgds.com/dyn/oh/Ow/ohOwXIWglMg/_/mQR5xLX5go8/m0Ys/coggles-logo.png', 'startDate': '2017-02-17', 'endDate': '2017-12-31', 'location': {'@type': 'Place','name': 'Coggles','url': 'coggles.co.uk','address': 'Coggles' }, 'description': 'Get the top branded fashion items from Coggles at discounted prices. Apply this code and enjoy savings on your purchase.', 'eventStatus': 'EventScheduled'}</script>
怎么用python正則從這段腳本中提取coggles.co.uk域名呢,望各路高手指點(diǎn)顯示下身手...
問(wèn)題解答
回答1:正則實(shí)現(xiàn)的話只要保證你的標(biāo)定/特征是唯一的就好。但是'url'這個(gè)標(biāo)志又不是唯一的。這個(gè)時(shí)候@prolifes的方法是很好的。
如果一定要正則實(shí)現(xiàn)呢,要用到零寬斷言(zero-width assertions),當(dāng)然這個(gè)詞的翻譯比較直,帶來(lái)很多誤解。它其實(shí)意思是指定位置的匹配,位置的寬度就是0嘛。
這里我們可以看到我們所需的這個(gè)'url'在'location'里面,可以以此為位置信息。
代碼如下:
re.search(’(?<=location).+?'url': '([^']+)'’, string, re.DOTALL).group(1)
稍微解釋一下,(?<=location)這個(gè)地方就是指前面得有l(wèi)ocation。后面有的話這樣寫:(?=location)re.DOTALL這個(gè)是必須的,因?yàn)檫@些字符串已經(jīng)跨行了。他的作用是將.的字符串匹配范圍擴(kuò)大,包含換行符。'([^']+)'這個(gè)地方是我的習(xí)慣,[^']意指所有非'的字符,這就匹配了雙引號(hào)中所有的字符串。
回答2:這是一段挺標(biāo)準(zhǔn)的json,粗暴一點(diǎn),直接轉(zhuǎn)換成json
import jsonstr = ’’’<script type='application/ld+json'>{ '@context': 'http://schema.org', '@type': 'SaleEvent', 'name': '10% Off First Orders', 'url': 'https://www.myvouchercodes.co.uk/coggles', 'image': 'https://mvp.tribesgds.com/dyn/oh/Ow/ohOwXIWglMg/_/mQR5xLX5go8/m0Ys/coggles-logo.png', 'startDate': '2017-02-17', 'endDate': '2017-12-31', 'location': {'@type': 'Place','name': 'Coggles','url': 'coggles.co.uk','address': 'Coggles' }, 'description': 'Get the top branded fashion items from Coggles at discounted prices. Apply this code and enjoy savings on your purchase.', 'eventStatus': 'EventScheduled'}</script>’’’d = json.loads(re.search(’({[sS]*})’, str).group(1))print d[’location’][’url’]
相關(guān)文章:
1. php怎么連接數(shù)據(jù)庫(kù)2. 在視圖里面寫php原生標(biāo)簽不是要迫不得已的情況才寫嗎3. 小皮面板MySQL怎么設(shè)置開(kāi)機(jī)自起呢4. 多種方式登陸的的用戶數(shù)據(jù)表設(shè)計(jì)5. 請(qǐng)問(wèn)這是jeson嗎?如何遍歷出來(lái)?6. 獲取上次登錄ip的原理是啥?7. 為什么點(diǎn)擊登陸沒(méi)反應(yīng)8. 為什么說(shuō)非對(duì)象調(diào)用成員函數(shù)fetch()9. phpstudy v8打開(kāi)數(shù)據(jù)庫(kù)就出錯(cuò),而phpstudy 2018不會(huì)10. 請(qǐng)問(wèn)下tp6框架的緩存在哪里設(shè)置,或者說(shuō)關(guān)閉?
