2017-08-11 92 views
2

给定以下字符串;在需要非贪婪匹配的情况下匹配正则表达式

我想匹配"And now for something completely different!"(Monty Python),通过引用引号和括号。在此示例中,"Hello"不应匹配,因为引号后没有括号。

非贪婪的方法看起来就像一条路可走:".*?"比赛"Hello""And now for something completely different!"分开,这是接近的,但如果我追加到这个支架,".*?"(.*),我结束了整个字符串匹配。

也就是说

"Hello", he said. "And now for something completely different!"(Monty Python) 

返回。

如何强制我的正则表达式按照我的要求行事?我在python中工作,所以可以选择使用lookahead/behind。

+0

要匹配字面括号,使用反斜线转义或放入类中,否则它们将打开捕获组。此外,我宁愿使用否定类而不是非贪婪点,它不会给你从最后的最短匹配。 –

回答

2

这工作:

"[^"]*"(:?\(.*\)) 

它查找一组引号(即没有引号之间) 后面跟着一组括号

1

你可以试试这个:

s = '"Hello", he said. "And now for something completely different!"(Monty Python).' 

import re 

new_data = re.findall('"(.*?)"', s) 

final_data = [i for i in new_data if len(re.findall("\w+(?=!)", i)) > 0][0] 

输出:

'And now for something completely different!'