[Python Study Notes]Regex

來源:互聯網
上載者:User

標籤:mat   .com   匹配   表達   模組   正則   log   根據   等等   

                      Regex                                                                      

 

Regex是一個特殊的字元序列,它能協助你方便的檢查一個字串是否與某種模式比對。

Python 自1.5版本起增加了re 模組,它提供 Perl 風格的Regex模式。

re 模組使 Python 語言擁有全部的Regex功能。

compile 函數根據一個模式字串和可選的標誌參數產生一個Regex對象。該對象擁有一系列方法用於Regex匹配和替換。

re 模組也提供了與這些方法功能完全一致的函數,這些函數使用一個模式字串做為它們的第一個參數。

本章節主要介紹Python中常用的Regex處理函數。

re.match函數

re.match 嘗試從字串的起始位置匹配一個模式,如果不是起始位置匹配成功的話,match()就返回none。

函數文法

re.match(pattern, string, flags=0)
參數 描述
pattern 匹配的Regex
string 要匹配的字串。
flags 標誌位,用於控制Regex的匹配方式,如:是否區分大小寫,多行匹配等等。

匹配成功re.match方法返回一個匹配的對象,否則返回None。

我們可以使用group(num) 或 groups() 匹配對象函數來擷取匹配運算式。

匹配對象方法 描述
group(num=0) 匹配的整個運算式的字串,group() 可以一次輸入多個組號,在這種情況下它將返回一個包含那些組所對應值的元組。
groups() 返回一個包含所有小組字串的元組,從 1 到 所含的小組號。

 

1 # -*- coding: UTF-8 -*- 2  3 import re4 print(re.match(‘www‘, ‘www.runoob.com‘).span())  # 在起始位置匹配5 print(re.match(‘com‘, ‘www.runoob.com‘))         # 不在起始位置匹配

 

 結果:

1 (0, 3)2 None

 

 

 1 import re 2   3 line = "Cats are smarter than dogs" 4   5 matchObj = re.match( r‘(.*) are (.*?) .*‘, line, re.M|re.I) 6   7 if matchObj: 8    print "matchObj.group() : ", matchObj.group() 9    print "matchObj.group(1) : ", matchObj.group(1)10    print "matchObj.group(2) : ", matchObj.group(2)11 else:12    print "No match!!"

 

結果 :

1 matchObj.group() :  Cats are smarter than dogs2 matchObj.group(1) :  Cats3 matchObj.group(2) :  smarter

 

[Python Study Notes]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.