要捕获任意组的项目,可以使用正则表达式来实现。在正则表达式中,使用括号()来表示一个组。可以使用以下方法来捕获任意组的项目:
import re
string = "Hello, my name is John. I am 25 years old."
pattern = r"(\w+)" # 匹配单词
matches = re.findall(pattern, string)
print(matches) # ['Hello', 'my', 'name', 'is', 'John', 'I', 'am', '25', 'years', 'old']
在上面的示例中,使用正则表达式(\w+)
来匹配所有的单词。re.findall()函数返回一个列表,其中包含所有匹配的项目。
import re
string = "Hello, my name is John. I am 25 years old."
pattern = r"(\w+)" # 匹配单词
matches = re.finditer(pattern, string)
for match in matches:
print(match.group()) # Hello my name is John I am 25 years old
在上面的示例中,使用正则表达式(\w+)
来匹配所有的单词。re.finditer()函数返回一个迭代器,可以使用循环逐个访问匹配的项目。通过match.group()方法获取当前匹配的项目。
注意:上述示例中的正则表达式只是一个简单的示例,可以根据具体需求来修改正则表达式来匹配不同的项目。