小编典典
获取python regex解析树以调试你的regex。
正则表达式是python的一个很棒的功能,但是调试它们可能会很麻烦,而且很容易使正则表达式出错。
幸运的是,python可以通过将未记录的,实验性的隐藏标志re.DEBUG(实际上是128个)传递给,从而输出正则表达式分析树re.compile。
>>> re.compile("^\[font(?:=(?P[-+][0-9]{1,2}))?\](.*?)[/font]",
re.DEBUG)
at at_beginning
literal 91
literal 102
literal 111
literal 110
literal 116
max_repeat 0 1
subpattern None
literal 61
subpattern 1
in
literal 45
literal 43
max_repeat 1 2
in
range (48, 57)
literal 93
subpattern 2
min_repeat 0 65535
any None
in
literal 47
literal 102
literal 111
literal 110
literal 116
一旦了解了语法,就可以发现错误。在那里,我们可以看到,我忘了躲避[]在[/font]。
当然,你可以将其与所需的任何标志(例如带注释的正则表达式)结合使用:
>>> re.compile("""
^ # start of a line
\[font # the font tag
(?:=(?P # optional [font=+size]
[-+][0-9]{1,2} # size specification
))?
\] # end of tag
(.*?) # text between the tags
\[/font\] # end of the tag
""", re.DEBUG|re.VERBOSE|re.DOTALL)
2020-02-10