Mozein
Mozein

Reputation: 807

Matching all words ending with s

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

Answers (3)

Malik Brahimi
Malik Brahimi

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

pzp
pzp

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

A.J. Uppal
A.J. Uppal

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

Related Questions