Python Regex 補充

來源:互聯網
上載者:User

標籤:開發   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 補充

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.