下面是一个示例代码,展示了如何按空格切割字符串并通过正则表达式匹配进行迭代:
import re
# 原始字符串
text = "Hello world! How are you today?"
# 按空格切割字符串
words = text.split()
# 正则表达式模式
pattern = r'o'
# 迭代匹配结果
for word in words:
matches = re.findall(pattern, word)
if matches:
print(f"在单词 '{word}' 中找到匹配的字符 '{pattern}': {matches}")
输出:
在单词 'Hello' 中找到匹配的字符 'o': ['o']
在单词 'world!' 中找到匹配的字符 'o': ['o']
在单词 'How' 中找到匹配的字符 'o': []
在单词 'are' 中找到匹配的字符 'o': []
在单词 'you' 中找到匹配的字符 'o': []
在单词 'today?' 中找到匹配的字符 'o': []
这个示例首先使用text.split()
方法按空格将字符串切割成单词列表。然后,使用re.findall()
方法和给定的正则表达式模式在每个单词中寻找匹配的字符。如果找到匹配的字符,就打印出匹配结果。