Skip to main content
 首页 » 编程设计

python之匹配所有以s结尾的单词

2025年05月04日15bhlsheji

我有一个程序可以编写一个正则表达式来匹配最后一个字母以 's' 结尾的所有单词。但是我遇到的问题是,它只匹配第一个单词,然后就停止了。所以如果我输入表达式: “詹姆斯对我们很好”

我希望

 matchObj.group() : 'james' 
 matchObj.group(1): 'is' 
 matchObj.group(2): 'us' 

但是我只得到 matchObj.group() : 'james'

我相信问题可以追溯到匹配函数的工作方式,是否有解决办法?这是我的代码

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)) 

请您参考如下方法:

您需要像这样使用re.findall 来匹配字符串中包含的所有对象:

words = re.findall(r'\b\w+s\b', your_string)