python正則怎么提取域名
問題描述
<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)顯示下身手...
問題解答
回答1:正則實(shí)現(xiàn)的話只要保證你的標(biāo)定/特征是唯一的就好。但是'url'這個(gè)標(biāo)志又不是唯一的。這個(gè)時(shí)候@prolifes的方法是很好的。
如果一定要正則實(shí)現(xiàn)呢,要用到零寬斷言(zero-width assertions),當(dāng)然這個(gè)詞的翻譯比較直,帶來很多誤解。它其實(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í)慣,[^']意指所有非'的字符,這就匹配了雙引號中所有的字符串。
回答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. javascript - node.js promise沒用2. golang - 用IDE看docker源碼時(shí)的小問題3. c++ - 如何正確的使用QWebEngineView?4. yii2中restful配置好后在nginx下報(bào)404錯(cuò)誤5. javascript - js 寫一個(gè)正則 提取文本中的數(shù)據(jù)6. 算法 - python 給定一個(gè)正整數(shù)a和一個(gè)包含任意個(gè)正整數(shù)的 列表 b,求所有<=a 的加法組合7. android 如何實(shí)現(xiàn)如圖中的鍵盤上的公式及edittext的內(nèi)容展示呢8. java - 我在用Struts2上傳文件時(shí),報(bào)以下錯(cuò)誤怎么回事?9. php自學(xué)從哪里開始?10. 有會apicloud 混合開發(fā)的朋友嗎?
