標籤: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符號與方法