python中正則表達式的使用方法
本文主要關于python的正則表達式的符號與方法。
findall: 找尋所有匹配,返回所有組合的列表
search: 找尋第一個匹配并返回
sub: 替換符合規(guī)律的內(nèi)容,并返回替換后的內(nèi)容
.:匹配除了換行符以外的任意字符
a = 'xy123'
b = re.findall('x...',a)
print(b)
# ['xy12']
*:匹配前一個字符0次或者無限次
a = 'xyxy123'
b = re.findall('x*',a)
print(b)
# ['x', '', 'x', '', '', '', '', '']
?:匹配前一個字符0次或者1次
a = 'xy123'
b = re.findall('x?',a)
print(b)
# ['x', '', '', '', '', '']
.*:貪心算法
b = re.findall('xx.*xx',secret_code)
print(b)
# ['xxIxxfasdjifja134xxlovexx23345sdfxxyouxx']
.*?:非貪心算法
c = re.findall('xx.*?xx',secret_code)
print(c)
# ['xxIxx', 'xxlovexx', 'xxyouxx']
():括號內(nèi)結(jié)果返回
d = re.findall('xx(.*?)xx',secret_code)
print(d)
for each in d:
print(each)
# ['I', 'love', 'you']
# I
# love
# you
re.S使得.的作用域包括換行符”\n”
s = '''sdfxxhello
xxfsdfxxworldxxasdf'''
d = re.findall('xx(.*?)xx',s,re.S)
print(d)
# ['hello\n', 'world']
對比findall與search的區(qū)別
s2 = 'asdfxxIxx123xxlovexxdfd'
f = re.search('xx(.*?)xx123xx(.*?)xx',s2).group(2)
print(f)
f2 = re.findall('xx(.*?)xx123xx(.*?)xx',s2)
print(f2[0][1])
# love
# love
雖然兩者結(jié)果相同,但是search是搭配group來得到第二個匹配,而findall的結(jié)果是[(‘I', ‘love')],包含元組的列表,所以需要f2[0][1]來引入。
sub的使用
s = '123rrrrr123'
output = re.sub('123(.*?)123','123%d123'%789,s)
print(output)
# 123789123
例如我們需要將文檔中的所有的png圖片改變路徑,即需要找到所有的 .png 結(jié)尾,再將其都加上路徑,
import re
def multiply(m):
# Convert group 0 to an integer.
v = m.group(0)
print(v)
# Multiply integer by 2.
# ... Convert back into string and return it.
print('basic/'+v)
return 'basic/'+v
結(jié)果如下
>>>autoencoder.png basic/autoencoder.png RNN.png basic/RNN.png rnn_step_forward.png basic/rnn_step_forward.png rnns.png basic/rnns.png rnn_cell_backprop.png basic/rnn_cell_backprop.png LSTM.png basic/LSTM.png LSTM_rnn.png basic/LSTM_rnn.png attn_mechanism.png basic/attn_mechanism.png attn_model.png basic/attn_model.png
仿照上面案例,我們可以方便的對我們的任務進行定制。
subn相比sub,subn返回元組,第二個元素表示替換發(fā)生的次數(shù):
import re
def add(m):
# Convert.
v = int(m.group(0))
# Add 2.
return str(v + 1)
# Call re.subn.
result = re.subn("\d+", add, "1 2 3 4 5")
print("Result string:", result[0])
print("Number of substitutions:", result[1])
>>>
Result string: 11 21 31 41 51
Number of substitutions: 5
相關文章
Pygame游戲開發(fā)之太空射擊實戰(zhàn)精靈的使用上篇
相信大多數(shù)8090后都玩過太空射擊游戲,在過去游戲不多的年代太空射擊自然屬于經(jīng)典好玩的一款了,今天我們來自己動手實現(xiàn)它,在編寫學習中回顧過往展望未來,下面開始講解精靈的使用2022-08-08
Django框架配置mysql數(shù)據(jù)庫實現(xiàn)過程
這篇文章主要介紹了Django框架配置mysql數(shù)據(jù)庫實現(xiàn)過程,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2020-04-04
Python使用open函數(shù)的buffering設置文件緩沖方式
這篇文章主要介紹了Python使用open函數(shù)的buffering設置文件緩沖方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-02-02
Python函數(shù)式編程指南(二):從函數(shù)開始
這篇文章主要介紹了Python函數(shù)式編程指南(二):從函數(shù)開始,本文講解了定義一個函數(shù)、使用函數(shù)賦值、閉包、作為參數(shù)等內(nèi)容,需要的朋友可以參考下2015-06-06

