python实用re模块来操作正则表达式,常用的方法如下:
- match:匹配字符串起始的n个字符,如果匹配,返回结果结果,否则返回None
- search:扫描整个字符串,返回第一个匹配的结果。
- findall:返回所有匹配结果
- sub:表示匹配并替换
看下面一段代码:
import re
content = "abacadae"
matcher = re.match("ab",content)#字符串开头是ab,匹配成功
print(matcher.span())
matcher = re.match("ac",content)#字符串开头不是ac,匹配失败
print(matcher)
matcher = re.search("ac",content)#字符串中扫描到ac,匹配成功
print(matcher.span())
matcher = re.findall("a.+?", content)#a.+? 表示a后有尽可能少的字符(非贪婪模式)
print(matcher)
matcher = re.findall("a.+", content)#a.+ 表示a后有尽可能多的字符(贪婪模式)
print(matcher)
matcher = re.sub("a.+?","xx",content)
print(matcher)
输出结果如下:
(0, 2)
None
(2, 4)
['ab', 'ac', 'ad', 'ae']
['abacadae']
xxxxxxxx