我有以下正则表达式:
(?P<question>.+(?<!\[\[))
它旨在匹配字符串hello world!
hello world! [[A string typically used in programming examples]]
然而我只匹配整个字符串,我无法弄清楚原因。我尝试了各种各样的环境,但它不会起作用......
任何人都知道如何解决这个问题?
谢谢,
CFP。
答案 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('[[')
而不是正则表达式会更容易。