py正則表達式 常用函數

re.match

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

  1. import re  
  2.   
  3. text = "JGood is a handsome boy, he is cool, clever, and so on..."  
  4. m = re.match(r"(/w+)/s", text)  
  5. if m:  
  6.     print m.group(0), '/n', m.group(1)  
  7. else:  
  8.     print 'not 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。

  1. import re  
  2.   
  3. text = "JGood is a handsome boy, he is cool, clever, and so on..."  
  4. m = re.search(r'/shan(ds)ome/s', text)  
  5. if m:  
  6.     print m.group(0), m.group(1)  
  7. else:  
  8.     print 'not search'  

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用於替換字符串中的匹配項。下面一個例子將字符串中的空格 ' ' 替換成 '-' :

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

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

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

 compile(string,file, type) 從type 類型中創建代碼對象;file 是代碼存放的地方(通常設
爲"")

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

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'的單詞用[]括起來

發佈了71 篇原創文章 · 獲贊 7 · 訪問量 9萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章