编译和未编译regex之间的Python regex差异

时间:2020-06-01 19:44:23

标签: python regex

我试图了解使用re.MULTILINE与不使用Python之间的区别。

具体来说,我看到使用带标志的编译模式时正则表达式的工作方式有所不同。在此示例中,我使用"blubber"作为输入字符串,并使用"^blubber$"作为匹配模式。这应该明显匹配。

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

测试脚本:

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

1 个答案:

答案 0 :(得分:3)

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

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

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