我有一个正则表达式模式,如果我用一行来写它,它就能很好地工作。
例如,如果我执行以下操作,模式就会工作:
MAIN_TREE_START_STRING_PATTERN = (
r"\*{3}\s+\bTotal Things\b:\s+(?P<number_of_things>\d+)"
)
compiled_pattern = re.compile(MAIN_TREE_START_STRING_PATTERN, flags=re.X)
match = compiled_pattern.match(string="*** Total Things: 348, abcdefghi ***")
if match:
print("Success")
else:
print("Failed")
但是如果我将regex模式更改为多行字符串,并使用VERBOSE
标志,它就不起作用了。
MAIN_TREE_START_STRING_PATTERN = r"""
\*{3}\s+\bTotal Things\b:\s+
(?P<number_of_things>\d+)
"""
compiled_pattern = re.compile(MAIN_TREE_START_STRING_PATTERN)
match = compiled_pattern.match(string="*** Total Things: 348, abcdefghi ***")
if match:
print("Success")
else:
print("Failed")
我不确定在多行模式声明期间我做错了什么。
2条答案
按热度按时间hwazgwia1#
您没有使用re.VERBOSE,在这种情况下必须显式匹配空格
ego6inou2#
多行字符串常量中的换行符也是结果字符串的一部分。额外的换行符很可能是正则表达式不再起作用的原因。
要去掉换行符,只需定义多个字符串,Python会自动将它们连接起来: