成人在线亚洲_国产日韩视频一区二区三区_久久久国产精品_99国内精品久久久久久久

您的位置:首頁技術(shù)文章
文章詳情頁

python re模塊常見用法例舉

瀏覽:125日期:2022-06-26 17:39:15

我們在用re模塊時,根據(jù)不同的使用需求,我們要挑選不同的函數(shù)來匹配??紤]到大家初學(xué)python,在對于方法的學(xué)習(xí)上,小編推薦以常見的方法為主要學(xué)習(xí)目標(biāo)。本篇所帶來的是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ù)。默認(rèn)為0,表示每個匹配項都替換。

re.sub還允許使用函數(shù)對匹配項的替換進(jìn)行復(fù)雜的處理。如:re.sub(r’/s’, lambda m: ’[’ + m.group(0) + ’]’, text, 0);將字符串中的空格’ ’替換為’[ ]’。

2、re.compile

可以把正則表達(dá)式編譯成一個正則表達(dá)式對象??梢园涯切┙?jīng)常使用的正則表達(dá)式編譯成正則表達(dá)式對象,這樣可以提高一定的效率。下面是一個正則表達(dá)式對象的一個例子:

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

到此這篇關(guān)于python re模塊常見用法例舉的文章就介紹到這了,更多相關(guān)python re模塊常見使用方法整理內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!

標(biāo)簽: Python 編程
相關(guān)文章: