Python 正则表达式匹配元组对

4

寻找匹配列表中元组对的正则表达式。一直在使用下面的正则表达式

s = '[(aleakedteaserand, NN), (abehind, IN), (the, DT)]'    
re.findall(r'\((.*,.*)\)',s)

但它仍然缺少结束括号。
['aleakedteaserand, NN), (abehind, IN), (the, DT']

期望的输出结果:

[(aleakedteaserand, NN), (abehind, IN), (the, DT)]


在预期输出中放置适当的引号。 - Mad Physicist
2个回答

10

你没有将正则表达式设置为非贪婪模式。解决方法是re.findall(r'\((.*?,.*?)\)',s)


为了获得问题中提到的预期输出,请将转义的 ( 移动到括号内部:re.findall(r'(\(.*?,.*?\))', s) - Wray Zheng
@Wray。不,OP想要匹配但不捕获括号。 - Mad Physicist
@Wray。预期输出中的括号和圆括号是findall在此情况下返回的元组列表。 - Mad Physicist

1

替代方案。第一个使用补集匹配,通常用作非贪婪搜索不可用时的替代方案。

>>> re.findall(r'\(([^)]*)\)',s)
['aleakedteaserand, NN', 'abehind, IN', 'the, DT']

>>> re.split('\), \(', s.strip('[()]'))
['aleakedteaserand, NN', 'abehind, IN', 'the, DT']

没有正则表达式。
>>> s.strip('[()]').split('), (')
['aleakedteaserand, NN', 'abehind, IN', 'the, DT']

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接