python正则表达式(re)的符号与方法.*()?,search,findall,sub

点号:匹配任意字符,\n除外
星号:匹配前一个字符,0次或无限次
问号:匹配前一个字符,0次或1次
括号:(),括号内的数据作为结果返回。例如当我们需要提出特定内容时,只需给相关内容加上括号

常用方法
findall:匹配所有符合规律的内容,返回包含结果的列表
search:匹配并提取第一个符合规律的内容,返回一个正则表达式的对象
sub:替换符合规律的内容,返回替换后的值

import re
a=‘xz123’
b=re.findall(‘x.’,a)
print(b)

c=‘xzbxy123’
d=re.findall(‘x*’,c)
print(d)

e=‘xz123’
f=re.findall(‘x?’,e)
print(f)

#.:贪吃法
secret_code=‘hadkfalifexxIxxfastdjifja134xxlovexx23345sdfxxyouxx8dfse’
g=re.findall('xx.xx’,secret_code)
print(g)
#.
?:少量多餐
h=re.findall('xx.
?xx’,secret_code)
print(h)

i=re.findall(‘xx(.*?)xx’,secret_code)
print(i)

s=’’‘sdfxxhello
xxfsdfxxworldxxasdf’’’

j=re.findall(‘xx(.*?)xx’,s,re.S)#re.S使点包含换行符
print(j)

k=re.findall(‘xx(.*?)xx’,s)#取消re.S后提取的是‘fsdf’
print(k)

#findall和research的区别
s2=‘asdexxIxx123xxlovexxdfd’
f1=re.search(‘xx(.?)xx123xx(.?)xx’,s2).group(1) #返回第一个括号里的值
print(f1)
f2=re.search(‘xx(.?)xx123xx(.?)xx’,s2).group(2) #返回第一个括号里的值
print(f2)

#sub实用案例,替换的功能
s3=‘123abcdssfastdfas123’
out1=re.sub(‘123(.*?)123’,‘123789123’,s3)
print(out1)

out2=re.sub(‘123(.*?)123’,‘123%d123’%789,s3)
print(out2)
======================== RESTART: /Users/bnz/test3.py ========================
[‘xz’]
[‘x’, ‘’, ‘’, ‘x’, ‘’, ‘’, ‘’, ‘’, ‘’]
[‘x’, ‘’, ‘’, ‘’, ‘’, ‘’]
[‘xxIxxfastdjifja134xxlovexx23345sdfxxyouxx’]
[‘xxIxx’, ‘xxlovexx’, ‘xxyouxx’]
[‘I’, ‘love’, ‘you’]
[‘hello\n’, ‘world’]
[‘fsdf’]
I
love
123789123
123789123

猜你喜欢

转载自blog.csdn.net/weixin_43055882/article/details/86573930
今日推荐