正则模块
匹配结果sre.Match包含如下方法或属性
方法(属性) 含义 match.group(index) 获取指定组的字符串 match.__getitem__(g) 即 match[0]=match.group(0) match.groups() 获取全部的组结果 match.span(index) 获取指定匹配结果字符串在string的截取段index match.start(groupindex) 获取指定子串组的起始位置 match.stop(groupindex) 获取指定子串组的结束位置 match.re 返回re对象,包含模式 match.string 返回原字符串 match.pos 返回传给正则表达式对象的 search()、match() 等方法的 pos 参数
方法:
re.compile(p, flag=0)
字符串(str)-->正则对象(_sre.SRE_Pattern)
比如一个程序需要多次使用同一个正则字符串,为了提高效率可以考虑先编译p = re.compile("baidu") # 编译正则对象p p.search("www.baidu.com") # 效率高 re.search("du", "www.baidu.com") # 效率低
re.match(p, string, flag=0)
检测是否开头匹配
成功返回re.Match对象,不成功则返回Nonere.fullmatch(p, string, flag=0)
检测p与string是否全文匹配
返回_sre对象,否则返回Nonere.search(p, string, flag=0)
扫描字符串查找匹配第一个子串
成功返回re.Match对象,不成功则返回None,匹配到第一个即停止re.findall(p, string, flag=0)
全文查找匹配所有子串
返回匹配到的子串列表re.finditer(p, string, flag=0)
迭代器类型的findall
re.sub(old, new, string, flag=0)
全文搜索p后用new替换掉
re.split(分割符, string, maxsplit=0, flag=0)
分割
通过分割符将string分割成列表类型, maxsplit指定分割次数*re.purge()
清除正则表达式缓存
re.escape(pattern)
对模式中除ASCII、数值、_外的字符进行转义,示例如下:
re.escape(r'www.baidu.com is good, i love') # 'www\\.baidu\\.com\\ is\\ good,\\ i\\ love'