Reputation: 43
There is a string
Mary loves Mike,Jack loves Lily,Ethan loves Lydia
I want to extract the names around each loves
with python.But the code below can't work.
names = re.search(r'(\S+) loves (\S+)',str, )
while names:
print names.group(1)
print names.group(2)
Upvotes: 1
Views: 75
Reputation: 391
You can use \w+ to extract words. And also since you want to extract all the matches, you can use a find all.
str="Mary loves Mike,Jack loves Lily,Ethan loves Lydia";
names = re.findall("(\w+) loves (\w+)", str)
for name in names:
print name
Upvotes: 1
Reputation: 133504
>>> 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')]
Upvotes: 9