我遇到了这种奇怪的行为,它在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)
我不清楚,为什么在第一个示例中捕获的header
是a
而不是this is a
,以及为什么在第二个示例中捕获失败。当使用search
而不是match
时,可以看到相同的行为
你知道如何像在regex101中那样完整地捕捉它吗
你用旗子作为起始位置。只有在编译regex时才能添加标志:
^{} 和^{} 的第二个参数是} ,即8。这意味着匹配从第8个字符开始
pos
。您传递的是^{相关问题 更多 >
编程相关推荐