search()函数会在整个字符串内查找模式匹配,直到找到第一个匹配,然后返回一个包含匹配信息的对象,该对象可以通过group()方法得到匹配的字符串,如果没有字符串没有匹配到,则返回None。
import re print(re.search("time", "datetime")) print(re.search("time", "datetime").span()) print(re.search("time1", "datetime")) print(re.search("hello", "hihelloworld").span()) print(re.search("hello", "hihelloworld").group()) # 结果 ''' <re.Match object; span=(4, 8), match='time'> (4, 8) None (2, 7) hello '''match()函数只检测字符串开头位置是否匹配,匹配成功才会返回结果,否则返回None。
group() 返回被 RE 匹配的字符串start() 返回匹配开始的位置end() 返回匹配结束的位置span()返回一个元组包含匹配 (开始,结束) 的位置 import re print(re.match("time", "datetime")) print(re.match("time", "timedate")) print(re.match("time", "timedate").span()) print(re.match("time", "timedate").group()) # 结果 ''' None <re.Match object; span=(0, 4), match='time'> (0, 4) time '''