python3正则表达式

正则表达式是一个特殊的字符序列,它能帮助你方便的检查一个字符串是否与某种模式匹配。re 模块使 Python 语言拥有全部的正则表达式功能。

import re
#re.match只匹配字符串的开始,如果字符串开始不符合正则表达式,则匹配失败,函数返回None;而re.search匹配整个字符串,直到找到一个匹配。

#re.match 尝试从字符串的起始位置匹配一个模式,如果不是起始位置匹配成功的话,match()就返回none。
print(re.match('www', 'www.runoob.com').span())
#不在起始位置匹配
print(re.match('com', 'www.runoob.com'))

line = 'Cat are smarter than dogs'
matchObj = re.match(r'(.*) are (.*?) (.*)', line, re.M|re.I)
if matchObj:
    print("matchObj.group() : ", matchObj.group())
    print("matchObj.group(1) : ", matchObj.group(1))
    print("matchObj.group(2) : ", matchObj.group(2))
    print("matchObj.group(3) : ", matchObj.group(3))
else:
    print("No match!!")

#re.search 扫描整个字符串并返回第一个成功的匹配。
print(re.search('www', 'www.runoob.com').span())
#不在起始位置匹配
print(re.search('com', 'www.runoob.com').span())

#re.sub用于替换字符串中的匹配项
phone = "2004-959-559 # 这是一个电话号码"
#删除注释
num = re.sub(r'#.*$', '', phone)
print('电话号码:', num)
#移除非数字的内容
num = re.sub(r'\D', '', phone)
print('电话号码:', num)

运行结果:

D:\python3.6.1\python.exe F:/python_Advanced/pattern.py
(0, 3)
None
matchObj.group() :  Cat are smarter than dogs
matchObj.group(1) :  Cat
matchObj.group(2) :  smarter
matchObj.group(3) :  than dogs
(0, 3)
(11, 14)
电话号码: 2004-959-559 
电话号码: 2004959559


Process finished with exit code 0


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

书灯

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值