Python与regex101/Python的奇重匹配行为

2024-05-16 05:46:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我遇到了这种奇怪的行为,它在regex101.com和Python设置中运行良好,但在实际的python3.7中无法捕获:

import re
match_str = r'(?P<header>.*?)(FROG)'
pattern_comment = re.compile( match_str )

# this sort of works
txt = 'this is a FROG'
matches = pattern_comment.match(txt, re.MULTILINE)
print(matches) # <re.Match object; span=(8, 14), match='a FROG'>
print(matches['header']) . # 'a '

# this fails to capture in python, but works in regex101
txt = 'this FROG'
matches = pattern_comment.match(txt, re.MULTILINE)
print(matches)

我不清楚,为什么在第一个示例中捕获的headera而不是this is a,以及为什么在第二个示例中捕获失败。当使用search而不是match时,可以看到相同的行为

你知道如何像在regex101中那样完整地捕捉它吗


Tags: retxtismatchcommentthisheadermultiline
1条回答
网友
1楼 · 发布于 2024-05-16 05:46:07

你用旗子作为起始位置。只有在编译regex时才能添加标志:

import re
match_str = r'(?P<header>.*?)(FROG)'
pattern_comment = re.compile(match_str, re.MULTILINE)

txt = 'this is a FROG'
matches = pattern_comment.match(txt)
print(matches)
print(matches['header'])

txt = 'this FROG'
matches = pattern_comment.match(txt)
print(matches)

^{}^{}的第二个参数是pos。您传递的是^{},即8。这意味着匹配从第8个字符开始

相关问题 更多 >