**explain:**python3中的re庫是一個正則匹配的函數庫,里面包含了各種功能的正則函數,下面,我們一起學習下其中的幾個常用函數
* **match()方法**:
從主串的起始位置開始匹配一個子串,匹配成功,返回匹配信息,不成功則返回NONE
print(re.match("www", "www.baidu.com"))
下面是返回的信息內容,包括子串的內容和子串在主串中的起始位置
<re.Match object; span=(0, 3), match='www'>
* **search()方法**:
從整個主串中匹配子串,與search方法相比,match方法更適合檢查某個字符串的開頭是否符合某個規定
print(re.search("com", "wwww.baidu.com"))
下面是返回的信息內容,與match方法一樣,但如果我們在這里使用match方法則會返回NONE,因為主串的開頭不是‘com’
<re.Match object; span=(11, 14), match='com'>
* **span()方法**:
只返回子串在主串中的起始位置,在match和search方法中都可使用
print(re.match('www', 'www.baidu.com').span())
下面是返回信息,是元組類型
(0, 3)
* **group()方法**:
與span方法類似,返回的是匹配的內容。
print(re.search("com", "www.baidu.com").group())
下面是返回信息
com
下面是一個運營group方法的栗子。
line = "Cats are smarter than dogs"
matchObj = re.match(r'(.*) are (.*?) .*', line, re.M | re.I)
if matchObj:
print("matchObj.group() : ", matchObj.group())#.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
* **findall()方法:**
以列表的形式返回主串中所有符合規則的的子串
s = 's5s45ad465a5da'
m = r'\d+'
n = re.findall(m, s)
print(n)
下面是運行結果:
['5', '45', '465', '5'],符合規則的相鄰字符被作為一個元素存到數組里。
* **finditer()方法:**
finditer找到匹配的所有的子串,並把它作為迭代器返回
s = '12 drumm44ers drumming, 11 ... 10 ...'
iter = re.finditer(r'\d+', s)
for i in iter:
print(i)
print(i.group())
print(i.span())
###上面就是一些re庫中常用的正則函數,下面給大家分享兩個網址,第一個是教你如何看懂復雜的正則表達式,第二個是一位大佬寫的更加詳細的python正則
教你看懂復雜的正則:[https://www.cnblogs.com/superstar/p/6638970.html](https://www.cnblogs.com/superstar/p/6638970.html)
詳解python正則:[https://www.cnblogs.com/tina-python/p/5508402.html](https://www.cnblogs.com/tina-python/p/5508402.html)
(ps:本人太菜,若有錯誤的地方歡迎大佬隨時責罵。。。。xixixii)