def match(pattern, string, flags=0):
"""Try to apply the pattern at the start of the string, returning
a match object, or None if no match was found."""
return _compile(pattern, flags).match(string)
def search(pattern, string, flags=0):
"""Scan through string looking for a match to the pattern, returning
a match object, or None if no match was found."""
return _compile(pattern, flags).search(string)
1、re.match()
从起始位置匹配一个符合规则的字符串,匹配成功返回一个对象,未匹配成功返回None,包含三个参数:
- pattern:正则匹配规则
- string:要匹配的字符串
- flags:匹配模式
match()方法一旦匹配成功,就是一个match object对象,具有以下方法:
- group():返回被re匹配的字符串
- start():返回匹配开始的位置
- end():返回匹配结束的位置
- span():返回一个元组包含匹配(开始,结束)的位置
example:
import re
# re.match 返回一个 match object 对象
# 对象提供了 group() 方法,来获取匹配的结果
result = re.match('hello', 'hello world')
if result:
print(result.group())
else:
print("匹配失败")
# 输出结果
# hello
2、re.search()
在字符串内查找匹配一个符合规则的字符串,只要找到第一个匹配的字符串就返回,如果字符串没有匹配,则返回None,参数与match类似,search同样具有和上面match相同的4个方法。
example:
import re
ret = re.search(r'\d+', '阅读次数为9999')
if ret:
print(ret.group())
else:
print("匹配失败!")
# 输出结果
# 9999
3、re.match() 和 re.search() 的区别
- match()函数只检测re是不是在string的开始位置匹配
- search()会扫描整个string查找匹配
- match()只有在起始位置匹配成功的话才会返回,如果不是起始位置匹配成功的话,match()就返回None
example:
import re
print(re.match('super', 'superstition').span())
# 输出结果:(0, 5)
print(re.match('super','insuperable'))
# 输出结果:None
print(re.search('super','superstition').span())
# 输出结果:(0, 5)
print(re.search('super','insuperable').span())
# 输出结果:(2, 7)