python与正则

python常用正则表达式

  1. re.compile(string[,flag])
  2. re.match(pattern,string[,flags])
  3. re.search(pattern,string[,flags])
  4. re.split(pattern,string[,maxsplit])
  5. re.findall(pattern,string[,flags])
  6. re.finditer(pattern,string[,flags])
  7. re.sub(pattern,repl,string[,flags])
  8. re.subn(pattern,repl,string[,count])

  • re.compile(string[,flag])
pattern = re.compile(r'\d+')
  • re.match(pattern,string[,flags])
import re
# 将正则表达式编译成pattern对象
pattern = re.compile(r'\d+')
# 使用re.match匹配文本,获取匹配结果,无法匹配时返回None
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对象
pattern = re.compile(r'\d+')
# 使用re.search匹配文本获取匹配结果;无法匹配时将返回None
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)
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值