PythonRegex符號與方法

來源:互聯網
上載者:User

標籤:Regex   python   

匯入re庫檔案

import re

 from re import findall,search,S


secret_code = ‘hadkfalifexxIxxfasdjifja134xxlovexx23345sdfxxyouxx8dfse‘   #紅色為待帶抓取內容


.的使用舉例

 a = ‘xy123‘

 b = re.findall(‘x...‘,a)

 print b          #執行後返回xy12,x...中“.”代表預留位置,幾個點就取x後幾位


*的使用舉例

 a = ‘xyxy123‘

 b = re.findall(‘x*‘,a)

 print b      

#執行後返回[‘x‘, ‘‘, ‘x‘, ‘‘, ‘‘, ‘‘, ‘‘],x*代表產生匹配x(0-無窮次)的列表,不匹配的產生Null 字元串‘‘



?的使用舉例

 a = ‘xy123x‘

 b = re.findall(‘x?‘,a)

 print b     

 #執行後返回[‘x‘, ‘‘, ‘‘, ‘‘, ‘‘, ‘x‘, ‘‘],x?代表產生匹配x(0-無窮次)的列表,和x*的區別是列表最後加一個Null 字元串‘‘



‘‘‘上面的內容全部都是只需要瞭解,需要掌握的只有下面這一種組合方式(.*?)‘‘‘


 #.*的使用舉例

 b = re.findall(‘xx.*xx‘,secret_code)

 print b

 # #.*?的使用舉例

 c = re.findall(‘xx.*?xx‘,secret_code)

 print c




 #使用括弧與不使用括弧的差別

 d = re.findall(‘xx(.*?)xx‘,secret_code)

 print d

 for each in d:

     print each


 s = ‘‘‘sdfxxhello

 xxfsdfxxworldxxasdf‘‘‘


 d = re.findall(‘xx(.*?)xx‘,s,re.S)

 print d



對比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]


sub的使用舉例

 s = ‘123rrrrr123‘

 output = re.sub(‘123(.*?)123‘,‘123%d123‘%789,s)

 print output


示範不同的匯入方法

 info = findall(‘xx(.*?)xx‘,secret_code,S)

 for each in info:

     print each


不要使用compile

 pattern = ‘xx(.*?)xx‘

 new_pattern = re.compile(pattern,re.S)

 output = re.findall(new_pattern,secret_code)

 print output


匹配數字

a = ‘asdfasf1234567fasd555fas‘

b = re.findall(‘(\d+)‘,a)

print b


本文出自 “My Space” 部落格,轉載請與作者聯絡!

PythonRegex符號與方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.