re是python對正則表達式的支持
1.re.match
作用:
嘗試從字符串的開始匹配一個模式
re.match的函數原型爲:
re.match(pattern, string, flags)
第一個參數是正則表達式,這裏爲"(\w+)\s",如果匹配成功,則返回一個Match,否則返回一個None;
第二個參數表示要匹配的字符串;
第三個參數是標緻位,用於控制正則表達式的匹配方式,如:是否區分大小寫,多行匹配等等。
例子:
text = "JGoodis a handsome boy, he is cool, clever, and so on..."
pa = re.compile("\w+")
ma = re.match(pa, text)
print ma.group()
輸出結果爲:JGood,匹配了第一個單詞
2.re.search
作用:
函數會在字符串內查找模式匹配,只到找到第一個匹配然後返回,如果字符串沒有匹配,則返回None。
re.search的函數原型爲:
re.search(pattern, string,flags)。每個參數的含意與re.match一樣。
re.match與re.search的區別:
re.match只匹配字符串的開始,如果字符串開始不符合正則表達式,則匹配失敗,函數返回None;而re.search匹配整個字符串,直到找到一個匹配。
例子:
text = " JGood is a handsome boy, he is cool, clever, and so on..." pa = re.compile("\w+") ma = re.search(pa, text)
輸出結果爲:JGood,匹配了第一個單詞,之前空格沒有匹配
3.re.sub
作用:
用於替換字符串中的匹配項
re.sub的函數原型爲:
re.sub(pattern, repl, string, count)
其中第二個函數是替換後的字符串;本例中爲'-'
第四個參數指替換個數。默認爲0,表示每個匹配項都替換。
例子:
text = " JGood is a handsome boy, he is cool, clever, and so on..." pa = re.compile("\w+([e|d])") su = re.sub(pa, "subText",text) print su
輸出結果爲:subText is a subText boy, subText is cool, subTextr, subText so on... 將所有e和d結尾的單詞全部替換成subText
4. re.split
作用:
可以使用re.split來分割字符串,如:re.split(r'\s+', text);將字符串按空格分割成一個單詞列表。
例子:
text = "JGood is a handsome boy, he is cool, clever, and so on..." pa = re.compile("[ *, ]+") sp = re.split(pa, text) print sp
輸出結果爲:['JGood', 'is', 'a', 'handsome', 'boy', 'he', 'is', 'cool','clever', 'and', 'so', 'on...'] 返回一個列表
5. re.findall
作用:
可以獲取字符串中所有匹配的字符串。如:re.findall(r'\w*oo\w*',text);獲取字符串中,包含'oo'的所有單詞。
例子:
text = "JGood is a handsome boy, he is cool, clever, and so on..." pa = re.compile("\w+") fa = re.findall(pa, text) print fa
輸出結果爲:['JGood', 'is', 'a', 'handsome', 'boy', 'he', 'is', 'cool','clever', 'and', 'so', 'on']
6. re.compile
作用:
可以把正則表達式編譯成一個正則表達式對象。可以把那些經常使用的正則表達式編譯成正則表達式對象,這樣可以提高一定的效率。