Skip to main content
 首页 » 编程设计

python之在 python 中使用正则表达式捕获重复组

2025年05月04日25kerrycode

例。 “史蒂夫 && 克里斯 || 乔 && 乔治”

Group[0] = steve && chris  
Group[1] = joe && george 

我可以找到第一组 (.*?)([|]{2}) 但如何找到下一组。

请记住,我希望它是动态的。字符串将以相同的模式增长。 对于前。

"steve && chris || joe && george || sep && geo" 

请您参考如下方法:

非 Regex 解决方案可以使用 str.split

>>> s = "steve && chris || joe && george" 
>>> tmp = s.split('||') 
>>> groups = map(str.strip,tmp) 
>>> groups 
['steve && chris', 'joe && george'] 

map和 str.strip这里用来清理组

它也是动态的

>>> s =  "steve && chris || joe && george || sep && geo" 
>>> tmp = s.split('||') 
>>> groups = map(str.strip,tmp) 
>>> groups 
['steve && chris', 'joe && george', 'sep && geo'] 

请注意,基本的字符串函数比 RegEx 解决方案运行得更快