在這篇文章之中我們來瞭解一下關於python之中的Regex,有些朋友可能是剛剛接觸到python這一程式設計語言,對於這一方面不是特別的瞭解,在接下來的文章之中我們來瞭解一下
python中re.match函數,
python re.match函數是Python中常用的Regex處理函數。廢話不多說,我們開始進入文章吧。
re.match函數:
re.match 嘗試從字串的起始位置匹配一個模式,如果不是起始位置匹配成功的話,match()就返回none。
函數的文法
re.match(pattern, string, flags=0)
函數參數說明:
匹配成功re.match方法返回一個匹配的對象,否則返回None。
我們可以使用group(num) 或 groups() 匹配對象函數來擷取匹配運算式。
執行個體如下:
#!/usr/bin/python# -*- coding: UTF-8 -*- import reprint(re.match('www', 'www.runoob.com').span()) # 在起始位置匹配print(re.match('com', 'www.runoob.com')) # 不在起始位置匹配
輸出如下:
(0, 3)None
# !/usr/bin/pythonimport reline = "Cats are smarter than dogs"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 dogsmatchObj.group(1) : CatsmatchObj.group(2) : smarter