有一个字符串

Mary loves Mike,Jack loves Lily,Ethan loves Lydia


我想用python提取每个loves周围的名称,但是下面的代码不起作用。

names = re.search(r'(\S+) loves (\S+)',str, )
while names:
    print names.group(1)
    print names.group(2)

最佳答案

>>> import re
>>> re.findall(r"([a-zA-Z]+) loves ([a-zA-Z]+)", "Mary loves Mike,Jack loves Lily,Ethan loves Lydia")
[('Mary', 'Mike'), ('Jack', 'Lily'), ('Ethan', 'Lydia')]

09-19 23:17