1. 程式人生 > 程式設計 >輕鬆入門正則表示式之非貪婪匹配篇詳解

輕鬆入門正則表示式之非貪婪匹配篇詳解

非貪婪匹配 (.*?)

import re
a = '456qwe789rty123abc'
re=re.findall('456(.*?)789',a)
print(re)

image-20211018145402204

http://www.cppcns.com常情況,滿足匹配規則“456(.*?)789”的內容通常不止一個,那麼findall()函式會從字串的起始位置開始尋找文字A,找到後開始尋找文字B,當找到第一個文字B後,暫時停止尋找,將文字A和文字B之間的內容存入列表;然後繼續尋找文字A,並重復之前的步驟,直到到達字串的結束位置,並將所有匹配到的內容存入列表。

import re
a = '456qwe789rty123456kkk789abc456xiaowang789'
re=re.findall('456(.*?)789',a)
print(re)

image-20211018145652096

貪婪模式的話就會尋找最長的

import re
a = '456qwe789rty123456kkk789abc456xiaowang789'
re=re.findall('456(.*)789',a)
print(re)

image-20211018145749767

非貪婪匹配 .*?

import re
a='<a href="https://blog.csdn.net/weixin_42403632/articletxxXYFVjD/details/120825546" rel="external nofollow"  target="_blank" data-report-click="{&quot;spm&quot;:&quot;3001.5501&quot;}" data-report-query="spm=3001.5501" data-v-6fe2b6a7="">'
re=re.findall('<a href="(.*?)" rel="external nofollow"  rel="external nofollowtxxXYFVjD
" .*?',a) print(re)

image-20211018150444488

" 和 url後面的html程式碼.*?代表,需要提取的是<a href="後的內容,用“(.*?)”代表

實戰爬取部落格專欄url

import re,requests
url='https://blog.csdn.net/weixin_42403632/category_11076268.html'
headers={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:93.0) Gecko/20100101 Firefox/93.0'}
html=requests.get(url,headers=headers).text

re=re.findall('<a href="(.*?)" rel="external nofollow"  rel="external notxxXYFVjD
follow" .*?rel="noopener">',html) for i in re: print(i)

image-20211018152344699

到此這篇關於輕鬆入門正則表示式之非貪婪匹http://www.cppcns.com配篇詳解的文章就介紹到這了,更多相關正則表示式 非貪婪匹配內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!