Python 正則表達式

1、python正則表達式包含在 ‘re’模塊中
 
一、導入re模塊:import re
 
二、re.match函數
re.match 從字符串的起始位置匹配一個模式,若是不是起始位置匹配成功的話,match()就返回none。
1 match = re.match('www', 'www.runoob.com')
2 print match.group(0)   #匹配結果
3 print match.span()     #匹配結果的起始和結束位置(0, 3)
三、re.search方法
re.search 掃描整個字符串並返回第一個成功的匹配
1 re.search('com', 'www.runoob.com')   #能夠匹配任意位置
2 print match.group(0)   #匹配結果
3 print match.span()     #匹配結果的起始和結束位置(0, 3)
四、檢索和替換
Python 的 re 模塊提供了re.sub用於替換字符串中的匹配項。
1 re.sub(pattern, repl, string, count=0, flags=0)
2 參數:
3   ● pattern : 正則中的模式字符串。
4   ● repl : 替換的字符串,也可爲一個函數。
5   ● string : 要被查找替換的原始字符串。
6   ● count : 模式匹配後替換的最大次數,默認 0 表示替換全部的匹配。
五、中文替換
  1 name = re.sub(u'\u60e0\u5dde\u5b66\u9662', u'清華大學', name); 
相關文章
相關標籤/搜索