標籤:開發 dem demo 貪婪模式 情況 print 爬蟲 font content
cuiqingcai大佬《Python3 網路爬蟲開發實戰》整理
貪婪與非貪婪
import recontent = ‘Hello 12345678 Word_This is a Regex Demo‘result = re.match(‘^He.*(\d+).*Demo$‘, content)print(result.group(1))
原本打算取出12345678,但
運行結果:8
貪婪匹配模式:.* 會匹配儘可能多的字元。
.*後(\d+)至少匹配一個數字,未指定具體數字。因此,.*儘可能匹配多的字元,把1234567匹配,給\d+留下一個僅滿足條件的結果8。
so,最後結果就至於8了。
非貪婪模式比對:.*? 儘可能匹配少的字元,餘下交給後面的去匹配。
在.*後加一個?
import recontent = ‘Hello 12345678 World_This is a Regex Demo‘result = re.match(‘^He.*?(\d+).*Demo$‘, content)print(result.group(1))
運行結果:12345678
所以,匹配時,字元中間盡量用非貪婪匹配,以免出現匹配結果確實的情況。若是匹配結果在字串結果,.*?有可能匹配不到任何內容,因為它會匹配儘可能少的字元。
import recontent = ‘http://weibo.com/comment/kEraCN‘result1 = re.match(‘^h.*?comment/(.*?)‘, content)result2 = re.match(‘^h.*?comment/(.*)‘, content)print(‘result1‘, result1.group(1))print(‘result2‘, result2.group(2))
Python Regex 補充