对于下面的代码:
t1 = 'tyler vs ryan'
p1 = re.compile('(.*?) vs (.*?)')
print p1.findall(t1)
输出是:
[('tyler', '')]
但我会预料到这一点:
[('tyler', 'ryan')]
我发现如果我添加一个定界符我可以让它工作:
t2 = 'tyler vs ryan!' # Notice the exclamation mark
p2 = re.compile('(.*?) vs (.*?)!') # Notice the exclamation mark
print p2.findall(t2)
输出:
[('tyler', 'ryan')]
有没有一种方法可以在没有自定义分隔符的情况下获得我的匹配项?
最佳答案
(.*?)
是非贪婪的,它将匹配最小的空字符串(至少在 vs
之后)
尝试 (.*)
或 ([^ ]*)
或其他东西
关于Python re 与上一个捕获组不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27368597/