Python的re应用

Python的re应用

 

 

 re的效果:

re.match是用来进行正则匹配检查的方法,若字符串匹配正则表达式,则match方法返回匹配对象(Match Object),否则返回None(注意不是空字符串"")。
匹配对象Macth Object具有group方法,用来返回字符串的匹配部分。

1单字符匹配

Python的re应用

 

 

 

ret = re.match("嫦娥d号","嫦娥3号发射成功")
print ret.group()

2.原生字符串

Python中字符串前面加上 r 表示原生字符串

3.表示数量

Python的re应用

 

 

 

4.边界

Python的re应用

 

 

 

163邮箱地址匹配
ret = re.match("[w]{4,20}@163.com", "xiaoWang@163.com")
ret.group()
ret = re.match("[w]{4,20}@163.com$", "xiaoWang@163.comheihei")
ret.group()

  ret = re.match("w{4,20}@(163|126|qq).com", "test@gmail.com")

  ret.group()


 

 

边界匹配
>>> re.match(r".*bverb", "ho ver abc").group()
'ho ver'
>>> re.match(r".*bverb", "ho verabc").group()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'group'

5.匹配分组

Python的re应用

6.高级用法

import re
ret = re.search(r"d+", "阅读次数为 9999")
ret.group()

ret = re.findall(r"d+", "python = 9999, c = 7890, c++ = 12345")
print ret

匹配替换
ret = re.sub(r"d+", '998', "python = 997")
print ret

匹配切割
ret = re.split(r":| ","info:xiaoZhang 33 shandong")
print ret

7.贪婪与非贪婪

在"*","?","+","{m,n}"后面加上?,使贪婪变成非贪婪

 

原文链接: https://www.cnblogs.com/topass123/p/12965418.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;

也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬

    Python的re应用

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/350995

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年3月2日 上午6:37
下一篇 2023年3月2日 上午6:38

相关推荐