How to get the regular expression to return all capture groups? [duplicate]

时间:2022-11-29 20:15:42

This question already has an answer here:

这个问题在这里已有答案:

So I have a string RAM 1000/2000/3000/4000 and I want to extract RAM 1000, 2000, 3000 and 4000 from it using regular expressions.

所以我有一个字符串RAM 1000/2000/3000/4000,我想使用正则表达式从中提取RAM 1000,2000,3000和4000。

So far I've (RAM 1000)(?:(?:\/)(\w+)){1,}, but it returns only RAM 1000 and 4000. How do I get it to return all the desired matches in Python?

到目前为止我(RAM 1000)(?:(?:\ /)(\ w +)){1,},但它只返回RAM 1000和4000.如何让它返回Python中所有想要的匹配?

1 个解决方案

#1


0  

While it does seem like str.split would do the job here, if you want to use regular expressions then you probably want to use re.findall:

虽然看起来str.split似乎可以在这里完成工作,但如果你想使用正则表达式,那么你可能想要使用re.findall:

>>> import re
>>> s = "RAM 1000/2000/3000/4000"
>>> re.findall(r"(?:RAM )?[^/]+", s)
['RAM 1000', '2000', '3000', '4000']

#1


0  

While it does seem like str.split would do the job here, if you want to use regular expressions then you probably want to use re.findall:

虽然看起来str.split似乎可以在这里完成工作,但如果你想使用正则表达式,那么你可能想要使用re.findall:

>>> import re
>>> s = "RAM 1000/2000/3000/4000"
>>> re.findall(r"(?:RAM )?[^/]+", s)
['RAM 1000', '2000', '3000', '4000']