国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

python中正則表達式的使用方法

2020-02-22 23:18:41
字體:
來源:轉載
供稿:網友

本文主要關于python的正則表達式的符號與方法。

findall: 找尋所有匹配,返回所有組合的列表
search: 找尋第一個匹配并返回
sub: 替換符合規律的內容,并返回替換后的內容
.:匹配除了換行符以外的任意字符

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']

():括號內結果返回

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 = '''sdfxxhelloxxfsdfxxworldxxasdf'''d = re.findall('xx(.*?)xx',s,re.S)print(d)# ['hello/n', 'world']

對比findall與search的區別

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

雖然兩者結果相同,但是search是搭配group來得到第二個匹配,而findall的結果是[(‘I', ‘love')],包含元組的列表,所以需要f2[0][1]來引入。

sub的使用

s = '123rrrrr123'output = re.sub('123(.*?)123','123%d123'%789,s)print(output)# 123789123

例如我們需要將文檔中的所有的png圖片改變路徑,即需要找到所有的 .png 結尾,再將其都加上路徑,

import redef 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

結果如下

>>>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返回元組,第二個元素表示替換發生的次數:

import redef 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 51Number of substitutions: 5            
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 彭山县| 福鼎市| 安泽县| 萨迦县| 邛崃市| 龙门县| 县级市| 搜索| 鸡西市| 宿迁市| 苍山县| 车险| 延津县| 伊金霍洛旗| 永泰县| 陇南市| 雷州市| 长顺县| 格尔木市| 友谊县| 蓬莱市| 闵行区| 杭锦旗| 财经| 元阳县| 罗田县| 乌拉特前旗| 鄂托克前旗| 青阳县| 弋阳县| 乐业县| 长顺县| 香港 | 永宁县| 巍山| 汤原县| 百色市| 菏泽市| 出国| 辽宁省| 曲麻莱县|