python筆記-Regex

來源:互聯網
上載者:User

標籤:python

Regex                                                                                                                                                   

  • 匹配

    \d 匹配一個數字

    \w 匹配一個字母

    \s 匹配一個空格或tab空白符

    [] 匹配一個範圍,例如[0-9a-zA-Z\_]可以匹配一個數字、字母或者底線

    . 表示任意一個字元

    ? 表示任意一個或零個字元


  • 個數

    + 表示其前面的字串至少出現了一次

    {n} 表示其前面的字串出現了n次

    {n,m} 可以表示其前面的字串出現了n-m次


  • 轉義

    \ 表示轉義

    r'' 引號中的特殊字元會被轉義(建議使用這種,不用考慮轉義問題)


  • re模組

match()方法 判斷是否匹配,如果匹配成功,返回一個Match對象,否則返回None。常見文法如下:

str = '使用者輸入的字串'if re.match(r'Regex', str):    print('ok')else:    print('failed')

例如:

#匹配ip地址import reif re.match(r'\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}','127.0.0.1'):    print('ok')else:    print('false')


  • 分組

() 小括弧中匹配的分為一組,常用功能:簡潔代碼、字串提取,例如:

#匹配ip地址,相同的部分寫成了一組import reif re.match(r'(\d{1,3}.){3}\d{1,3}','127.0.0.1'):    print('ok')else:    print('false')
#識別時間,提取小時、分鐘、秒import ret = '23:05:30'm = re.match(r'^(0[0-9]|1[0-9]|2[0-3]|[0-9]):(0[0-9]|1[0-9]|2[0-9]|3[0-9]|4[0-9]|5[0-9]|[0-9]):(0[0-9]|1[0-9]|2[0-9]|3[0-9]|4[0-9]|5[0-9]|[0-9])$', t)print (m.groups())




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.