re的效果:
re.match是用来进行正则匹配检查的方法,若字符串匹配正则表达式,则match方法返回匹配对象(Match Object),否则返回None(注意不是空字符串"")。 匹配对象Macth Object具有group方法,用来返回字符串的匹配部分。
1单字符匹配
ret = re.match("嫦娥\d号","嫦娥3号发射成功") print ret.group()
2.原生字符串
Python中字符串前面加上 r 表示原生字符串
3.表示数量
4.边界
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".*\bver\b", "ho ver abc").group()
'ho ver'
>>> re.match(r".*\bver\b", "ho verabc").group()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'group'
5.匹配分组
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}"后面加上?,使贪婪变成非贪婪
本文来自博客园,作者:topass123,转载请注明原文链接:https://www.cnblogs.com/topass123/p/12965418.html