Skip to main content
 首页 » 编程设计

python之如何只捕获析取的匹配端

2024年10月25日12fff_TT

以下代码:

re.findall('(a).(b)|(c).(d)','axbcyd') 

捕获两个匹配项,均带有两个空字符串:

[('a', 'b', '', ''), ('', '', 'c', 'd')] 

我想返回:

[('a', 'b'), ('c', 'd')] 

本质上,只捕获实际匹配的析取的一侧。我怎样才能做到这一点?对完全不同的方法感到满意...

请您参考如下方法:

正如 Avinash Raj 所说;只需删除空元素:

map(lambda x: tuple(filter(lambda y: y!='',x)),re.findall('(a).(b)|(c).(d)','axbcyd')) 

(编辑:更少的功能,更多的 pythonic:

[tuple(y for y in x if y != '') for x in re.findall('(a).(b)|(c).(d)','axbcyd')] 

)