標籤: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