re.match 嘗試從字符串的起始位置匹配一個模式,如果不是起始位置匹配成功的話,match()就返回none。
函數語法:
re.match(pattern, string, flags=0)
函數參數說明:
參數 | 描述 |
---|---|
pattern | 匹配的正則表達式 |
string | 要匹配的字符串。 |
flags | 標志位,用於控制正則表達式的匹配方式,如:是否區分大小寫,多行匹配等等。參見:正則表達式修飾符 - 可選標志 |
匹配成功re.match方法返回一個匹配的對象,否則返回None。
我們可以使用group(num) 或 groups() 匹配對象函數來獲取匹配表達式。
匹配對象方法 | 描述 |
---|---|
group(num=0) | 匹配的整個表達式的字符串,group() 可以一次輸入多個組號,在這種情況下它將返回一個包含那些組所對應值的元組。 |
groups() | 返回一個包含所有小組字符串的元組,從 1 到 所含的小組號。 |
實例
#!/usr/bin/python import re print(re.match('www', 'www.runoob.com').span()) # 在起始位置匹配 print(re.match('com', 'www.runoob.com')) # 不在起始位置匹配
以上實例運行輸出結果為:
(0, 3) None
實例
#!/usr/bin/python3 import re line = "Cats are smarter than dogs" # .* 表示任意匹配除換行符(\n、\r)之外的任何單個或多個字符 matchObj = re.match( r'(.*) are (.*?) .*', line, re.M|re.I) if matchObj: print ("matchObj.group() : ", matchObj.group()) print ("matchObj.group(1) : ", matchObj.group(1)) print ("matchObj.group(2) : ", matchObj.group(2)) else: print ("No match!!")
以上實例執行結果如下:
matchObj.group() : Cats are smarter than dogs matchObj.group(1) : Cats matchObj.group(2) : smarter