实例
#!/usr/bin/python3importreprint(re.search('www', 'www.runoob.com').span()) # 在起始位置匹配print(re.search('com', 'www.runoob.com').span()) # 不在起始位置匹配
以上实例运行输出结果为:
(0,3)
(11,14)
实例
#!/usr/bin/python3importreline = "Cats are smarter than dogs"searchObj = re.search(r'(.*) are (.*?) .*', line, re.M|re.I)ifsearchObj: print("searchObj.group() : ", searchObj.group()) print("searchObj.group(1) : ", searchObj.group(1)) print("searchObj.group(2) : ", searchObj.group(2))else: print("Nothing found!!")
以上实例执行结果如下:
searchObj.group(): Cats are smarter than dogs
searchObj.group(1): Cats
searchObj.group(2): smarter