1. 程式人生 > >Python中re(正則表示式)模組學習

Python中re(正則表示式)模組學習

歡迎加入Python學習交流QQ群:535993938  禁止閒聊 ! 名額有限 ! 非喜勿進 !


關於正則表示式的語法,不作過多解釋,網上有許多學習的資料。這裡主要介紹Python中常用的正則表示式處理函式。

re.match

  re.match 嘗試從字串的開始匹配一個模式,如:下面的例子匹配第一個單詞。 

複製程式碼 import re
text
="JGood is a handsome boy, he is cool, clever, and so on..."
m
= re.match(r"(\w+)\s", text)
if m:
print m.group(0),
'\n', m.group(1)
else:
print'not match' 複製程式碼

re.match的函式原型為:re.match(pattern, string, flags)

第一個引數是正則表示式,這裡為"(\w+)\s",如果匹配成功,則返回一個Match,否則返回一個None;

第二個引數表示要匹配的字串;

第三個引數是標緻位,用於控制正則表示式的匹配方式,如:是否區分大小寫,多行匹配等等。

re.search

  re.search函式會在字串內查詢模式匹配,只到找到第一個匹配然後返回,如果字串沒有匹配,則返回None。

複製程式碼 import re
text
="JGood is a handsome boy, he is cool, clever, and so on...
"
m
= re.search(r'\shan(ds)ome\s', text)
if m:
print m.group(0), m.group(1)
else:
print'not search' 複製程式碼

re.search的函式原型為: re.search(pattern, string, flags)

每個引數的含意與re.match一樣。 

re.match與re.search的區別:re.match只匹配字串的開始,如果字串開始不符合正則表示式,則匹配失敗,函式返回None;而re.search匹配整個字串,直到找到一個匹配。

re.sub

  re.sub用於替換字串中的匹配項。下面一個例子將字串中的空格 ' ' 替換成 '-' :  

import re
text
="JGood is a handsome boy, he is cool, clever, and so on..."print re.sub(r'\s+', '-', text)

 re.sub的函式原型為:re.sub(pattern, repl, string, count)

其中第二個函式是替換後的字串;本例中為'-'

第四個引數指替換個數。預設為0,表示每個匹配項都替換。

re.sub還允許使用函式對匹配項的替換進行復雜的處理。如:re.sub(r'\s', lambda m: '[' + m.group(0) + ']', text, 0);將字串中的空格' '替換為'[ ]'。

re.split

  可以使用re.split來分割字串,如:re.split(r'\s+', text);將字串按空格分割成一個單詞列表。

re.findall

  re.findall可以獲取字串中所有匹配的字串。如:re.findall(r'\w*oo\w*', text);獲取字串中,包含'oo'的所有單詞。

re.compile

  可以把正則表示式編譯成一個正則表示式物件。可以把那些經常使用的正則表示式編譯成正則表示式物件,這樣可以提高一定的效率。下面是一個正則表示式物件的一個例子:

import re
text
="JGood is a handsome boy, he is cool, clever, and so on..."
regex
= re.compile(r'\w*oo\w*')
print regex.findall(text) #查詢所有包含'oo'的單詞print regex.sub(lambda m: '['+ m.group(0) +']', text) #將字串中含有'oo'的單詞用[]括起來。

歡迎加入Python學習交流QQ群:535993938  禁止閒聊 ! 名額有限 ! 非喜勿進 !