已编译和未编译正则表达式之间的Python正则表达式差异

已编译和未编译正则表达式之间的Python正则表达式差异,python,regex,Python,Regex,我试图理解在Python中使用re.MULTILINE和不使用它之间的区别 具体来说,我看到了使用带标志的编译模式时regexp的工作方式之间的差异。在本例中,我使用“blubber”作为输入字符串,使用“^blubber$”作为匹配模式。这显然应该是一致的 在将re.MULTILINE传递给已编译的正则表达式对象的match方法时,尝试不同的组合会返回None。为什么会这样 测试脚本: import re import sys print(sys.version) input_string

我试图理解在Python中使用
re.MULTILINE
和不使用它之间的区别

具体来说,我看到了使用带标志的编译模式时regexp的工作方式之间的差异。在本例中,我使用
“blubber”
作为输入字符串,使用
“^blubber$”
作为匹配模式。这显然应该是一致的

在将
re.MULTILINE
传递给已编译的正则表达式对象的match方法时,尝试不同的组合会返回
None
。为什么会这样

测试脚本:

import re
import sys

print(sys.version)

input_string = "blubber"
matching_pattern = "^blubber$"


result_one = re.match(matching_pattern, input_string)
print("re.match:                            %r" % (result_one,))

result_two = re.match(matching_pattern, input_string, re.M)
print("re.match multiline:                  %r" % (result_two,))


compiled_re = re.compile(matching_pattern)
result_three = compiled_re.match(input_string)
print("compiled match:                      %r" % (result_three,))

compiled_re = re.compile(matching_pattern)
result_four = compiled_re.match(input_string, re.M)
print("compiled match multiline:            %r" % (result_four,))


compiled_re = re.compile(matching_pattern, re.M)
result_five = compiled_re.match(input_string)
print("compiled multiline match:            %r" % (result_five,))

compiled_re = re.compile(matching_pattern, re.M)
result_six = compiled_re.match(input_string, re.M)
print("compiled multiline match multiline:  %r" % (result_six,))
运行输出示例:

$ python3.8 wat_the_re.py 
3.8.3 (default, May 19 2020, 14:59:28) 
[GCC 8.3.0]
re.match:                            <re.Match object; span=(0, 7), match='blubber'>
re.match multiline:                  <re.Match object; span=(0, 7), match='blubber'>
compiled match:                      <re.Match object; span=(0, 7), match='blubber'>
compiled match multiline:            None
compiled multiline match:            <re.Match object; span=(0, 7), match='blubber'>
compiled multiline match multiline:  None
$python3.8 wat\u re.py
3.8.3(默认,2020年5月19日,14:59:28)
[GCC 8.3.0]
关于比赛:
重新匹配多行:
编译匹配:
编译匹配多行:无
编译的多行匹配:
编译的多行匹配多行:无

pattern.match()的第二个命名参数不是flags,而是匹配位置。由于
re.M
的值为8,因此从第九个位置开始匹配模式。您应该按名称传递标志:

result_six = compiled_re.match(input_string, flags=re.M)

而且,您已经使用该标志编译了模式,无需再次传递。

您完全正确,先生。