python中的re(正規表示式)

大菜鳥一號發表於2016-12-07

re是python對正規表示式的支援

1re.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,匹配了第一個單詞

 

2re.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

作用:

可以把正規表示式編譯成一個正規表示式物件。可以把那些經常使用的正規表示式編譯成正規表示式物件,這樣可以提高一定的效率。


相關文章