Reputation: 807
I have a program that write a regular expression to match all the words where last letter ends with 's' . However the problem that I am having is, it is matching only the first word, and then it stops. so if I enter the expression: "james is great with us"
I expect
matchObj.group() : 'james'
matchObj.group(1): 'is'
matchObj.group(2): 'us'
However I get only matchObj.group() : 'james'
I believe the problem goes back to the way match function works, is there a fix around it ? here is my code
import re
matchObj = re.match(r'\w+s', expression, re.M|re.I)
print("matchObj.group() : ", matchObj.group())
print("matchObj.group(1) : ", matchObj.group(1))
print("matchObj.group(2) : ", matchObj.group(2))
Upvotes: 1
Views: 4324
Reputation: 16711
You need to use re.findall
like so to match all the objects contained withing a string:
words = re.findall(r'\b\w+s\b', your_string)
Upvotes: 5
Reputation: 6607
I like @A.J.'s list comprehension better than this solution, but for those that like functional programming:
sentence = 'james is great with us'
print filter(lambda s: s.endswith('s'), sentence.split())
#OUT: ['james', 'is', 'us']
Upvotes: 0
Reputation: 19264
You can just use a list comprehension:
sentence = "james is great with us"
new = [word for word in sentence.split() if word[-1] == "s"]
Upvotes: 2