python中Regex的使用方法,pythonRegex

來源:互聯網
上載者:User

python中Regex的使用方法,pythonRegex

本文主要關於python的Regex的符號與方法。

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.