Python -- 正則表達式

一、python正則表達式包含在 ‘re’模塊中

1、導入re模塊:import re

 

2、re.match函數

re.match 從字符串的起始位置匹配一個模式,如果不是起始位置匹配成功的話,match()就返回none。

match = re.match('www', 'www.runoob.com')
print match.group(0)   #匹配結果
print match.span()     #匹配結果的起始和結束位置(0, 3)

 

3、re.search方法

re.search 掃描整個字符串並返回第一個成功的匹配

re.search('com', 'www.runoob.com')   #可以匹配任意位置
print match.group(0)   #匹配結果
print match.span()     #匹配結果的起始和結束位置(0, 3)

 

4、檢索和替換

Python 的 re 模塊提供了re.sub用於替換字符串中的匹配項。

re.sub(pattern, repl, string, count=0, flags=0)
參數:
     ● pattern : 正則中的模式字符串。
     ● repl : 替換的字符串,也可爲一個函數。
     ● string : 要被查找替換的原始字符串。
     ● count : 模式匹配後替換的最大次數,默認 0 表示替換所有的匹配。

 

5、中文替換

name = re.sub(u'\u60e0\u5dde\u5b66\u9662', u'清華大學', name); 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章