python re.search方法

re.search方法

re.search 扫描整个字符串并返回第一个成功的匹配。

函数语法:

re.search(pattern, string, flags=0)

匹配成功re.search方法返回一个匹配的对象,否则返回None。

我们可以使用group(num) 或 groups() 匹配对象函数来获取匹配表达式。

实例

#!/usr/bin/python3
import re
print(re.search('www', 'www.runoob.com').span()) # 在起始位置匹配
print(re.search('com', 'www.runoob.com').span()) # 不在起始位置匹配

以上实例运行输出结果为:

(0, 3)
(11, 14)

实例

#!/usr/bin/python3
import re line = "Cats are smarter than dogs"
searchObj = re.search( r'(.*) are (.*?) .*', line, re.M|re.I)
if searchObj:
  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
原文地址:https://www.cnblogs.com/wangdayang/p/14914775.html