python re模塊常見用法例舉
我們在用re模塊時,根據不同的使用需求,我們要挑選不同的函數來匹配。考慮到大家初學python,在對于方法的學習上,小編推薦以常見的方法為主要學習目標。本篇所帶來的是re.sub和re.compile兩種函數,下面就這兩個部分分別展開講解,具體內容如下展開。
1、re.subre.sub用于替換字符串中的匹配項。下面一個例子將字符串中的空格 ’ ’ 替換成 ’-’ :
import re text = 'JGood is a handsome boy, he is cool, clever, and so on...' 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);將字符串中的空格’ ’替換為’[ ]’。
2、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’的單詞用[]括起來。
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 re模塊常見用法例舉的文章就介紹到這了,更多相關python re模塊常見使用方法整理內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!
相關文章: