遇到一系列字符时停止匹配:修复后视

时间:2010-04-03 08:11:23

标签: regex negative-lookbehind lookaround

我有以下正则表达式:

(?P<question>.+(?<!\[\[))

它旨在匹配字符串hello world!

中的hello world! [[A string typically used in programming examples]]

然而我只匹配整个字符串,我无法弄清楚原因。我尝试了各种各样的环境,但它不会起作用......

任何人都知道如何解决这个问题?

谢谢,
CFP。

1 个答案:

答案 0 :(得分:3)

您只是检查匹配结束时的外观,这意味着它可以首先匹配尽可能多的字符串,然后检查外观。由于您在字符串末尾没有[[,因此匹配成功。

如果你真的想在这里使用正则表达式,你需要做的是检查你添加的每个字符的外观,如下所示:

>>> s = 'hello world! [[A string typically used in programming examples]]'
>>> regex = re.compile('(?P<question>((?!\[\[).)+)')
>>> regex.match(s).group('question')
'hello world! '

但请注意,在这里使用s.find('[[')而不是正则表达式会更容易。