re.match只匹配字符串的开始,如果字符串开始不符合正则表达式,则匹配失败,函数返回None;而re.search匹配整个字符串,直到找到一个匹配。

re.search(pattern, string, flags=0)
Flags可选为下面的基业
简写 全名 注释
I IGNORECASE 忽略大小写
M MULTILINE 多行模式
S DOTALL 单选模式——点任意匹配模式
L LOCALE 使预定字符类 \w \W \b \B \s \S 取决于当前区域设定
U UNICODE 使预定字符类 \w \W \b \B \s \S \d \D 取决于unicode定义的字符属性
X VERBOSE 详细模式。该模式下正则表达式可以是多行,忽略空白字符,并可以加入注释

 

#!/usr/bin/python3
import re

line = "Cats are smarter than dogs"

matchObj = re.match( r'(.*) are (.*?) .*', line, re.M|re.I)

if matchObj:
   print ("matchObj.group() : ", matchObj.group())
   print ("matchObj.group(1) : ", matchObj.group(1))
   print ("matchObj.group(2) : ", matchObj.group(2))
else:
   print ("No match!!")