python常用正则表达式
- re.compile(string[,flag])
- re.match(pattern,string[,flags])
- re.search(pattern,string[,flags])
- re.split(pattern,string[,maxsplit])
- re.findall(pattern,string[,flags])
- re.finditer(pattern,string[,flags])
- re.sub(pattern,repl,string[,flags])
- re.subn(pattern,repl,string[,count])
- re.compile(string[,flag])
pattern = re.compile(r'\d+')
- re.match(pattern,string[,flags])
import re
pattern = re.compile(r'\d+')
result1 = re.match(pattern,'192abc')
if result1:
print(result1.group())
else:
print('匹配失败1')
result2 = re.match(pattern,'abc122')
if result2:
print(result2.group())
else:
print('匹配失败2')
- re.search(pattern,string[,flags])
import re
pattern = re.compile(r'\d+')
result = re.search(pattern,'abc123wef')
if result:
print(result.group())
else:
print('error')
- re.split(pattern,string[,maxsplit])
pattern = re.compile(r'\d+')
print(re.split(pattern,'A1b2n3n5n7'))
- re.findall(pattern,string[,flags])
print(re.findall(pattern,'a1b2c3d4'))
- re.finditer(pattern,string[,flags])
matchiter = re.finditer(pattern,'a1b2c3d4')
for match in matchiter:
print(match.group())
- re.sub(pattern,repl,string[,flags])
p = re.compile(r'(?P<word1>\w+) (?P<word2>\w+)')
s = 'i say, hello world!'
printp.sub(r'\g<word2> \g<word1>', s)
p = re.compile(r'(\w+) (\w+)')
printp.sub(r'\2 \1',s)
def func(m):
returnm.group(1).title() + ' '+ m.group(2).title()
printp.sub(func, s)
- re.subn(pattern,repl,string[,count])
s = 'i say, hello world!'
p = re.compile(r'(\w+) (\w+)')
printp.subn(r'\2 \1',s)
def func(m):
returnm.group(1).title() + ' '+ m.group(2).title()
printp.subn(func, s)