我們在用re模塊時,根據(jù)不同的使用需求,我們要挑選不同的函數(shù)來匹配??紤]到大家初學python,在對于方法的學習上,小編推薦以常見的方法為主要學習目標。本篇所帶來的是re.sub和re.compile兩種函數(shù),下面就這兩個部分分別展開講解,具體內(nèi)容如下展開。
1、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)
import re text = "JGood is a handsome boy, he is cool, clever, and so on..." print re.sub(r'/s+', '-', text)
re.sub的函數(shù)原型為:re.sub(pattern, repl, string, count)
其中第二個函數(shù)是替換后的字符串;本例中為'-'
第四個參數(shù)指替換個數(shù)。默認為0,表示每個匹配項都替換。
re.sub還允許使用函數(shù)對匹配項的替換進行復雜的處理。如:re.sub(r'/s', lambda m: '[' + m.group(0) + ']', text, 0);將字符串中的空格' '替換為'[ ]'。
2、re.compile
可以把正則表達式編譯成一個正則表達式對象。可以把那些經(jīng)常使用的正則表達式編譯成正則表達式對象,這樣可以提高一定的效率。下面是一個正則表達式對象的一個例子:
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模塊常見使用方法整理內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
您可能感興趣的文章:- python copy模塊中的函數(shù)實例用法
- Python多線程 Queue 模塊常見用法
- Python中os模塊的實例用法
- Python協(xié)程asyncio模塊的演變及高級用法
- python常見模塊與用法
- Python寫腳本常用模塊OS基礎用法詳解
- python 中os模塊os.path.exists()的用法說明
- 詳解Python中openpyxl模塊基本用法
- Python常用的模塊和簡單用法