>之后的Python正则表达式匹配使用积极的lookbehind

时间:2014-02-14 19:02:29

标签: python regex

所以我想要匹配

something something bar<TEST> blah blah </TEST> foo

我想提取foo,我正在使用这个正则表达式

(?<=</\w+>)(\s\w)

为什么不工作?我得到一个空列表。我收到此错误 -

sre_constants.error: look-behind requires fixed-width pattern

2 个答案:

答案 0 :(得分:1)

嗯,你不能在这里使用外观,因为理想的使用是一个积极的外观,并确保后面有</\w+>之类的东西。在C#中,您可以使用(?<=</\w+>)(\s*\w+)之类的东西,但python不支持可变宽度的lookbehinds。剩下要做的可能是在比赛中包括</\w+>并使用捕获组:

</[^<>]*>\s*(\w+)

regex101 demo

请注意,[^<>]<之间>通常更安全。

答案 1 :(得分:0)

因为你想要一个外观,但不幸的是not many libraries support quantifiers in a lookbehind。你也有一些错误/错别字:

(?<=</\w+>)\s*(\w+)