在代码中保持使用相同的正则表达式进行查找字符串,可以使用函数封装的方式来实现。下面是一个示例代码:
import re
def find_string(pattern, text):
matches = re.findall(pattern, text)
return matches
# 示例用法
text = "Hello, my email is john@example.com and my phone number is 123-456-7890"
email_pattern = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b'
phone_pattern = r'\b\d{3}-\d{3}-\d{4}\b'
email_matches = find_string(email_pattern, text)
phone_matches = find_string(phone_pattern, text)
print("Email matches:", email_matches)
print("Phone matches:", phone_matches)
在上述示例中,find_string
函数接受一个正则表达式模式和一个文本字符串作为参数,并使用 re.findall
函数来查找匹配的字符串。通过这种方式,可以在代码中多次调用 find_string
函数,而无需重复编写正则表达式。
输出结果为:
Email matches: ['john@example.com']
Phone matches: ['123-456-7890']
使用这种方法,可以保持代码的一致性,并且方便地在多个地方重复使用相同的正则表达式进行字符串查找。
下一篇:保持手风琴状态在回发时。