下面是一个使用Python中的re模块来进行正则表达式匹配和文本搜索的示例:
import re
# 正则表达式匹配示例
pattern = r'abc' # 匹配字符串中的 "abc"
text = 'abcdefg'
result = re.findall(pattern, text)
print(result) # 输出: ['abc']
# 文本搜索示例
pattern = r'apple' # 搜索文本中的 "apple"
text = 'I have an apple and an orange.'
result = re.search(pattern, text)
if result:
print('Found') # 输出: Found
else:
print('Not found')
在上面的示例中,使用了re.findall()
函数来找到所有匹配的字符串。该函数返回一个包含所有匹配的字符串的列表。使用re.search()
函数来搜索文本中的第一个匹配项。如果找到匹配项,re.search()
函数返回一个匹配对象,否则返回None
。
你可以根据自己的需求修改正则表达式和文本,以获得不同的匹配和搜索结果。