在编程的世界里,模式匹配是一种强大的工具,它允许开发者从复杂的数据结构中提取信息,或者验证数据是否符合特定的格式。无论是编写正则表达式进行文本处理,还是使用编程语言内置的模式匹配功能,掌握这一技能都能显著提高编程效率。以下是一些习题,帮助你更好地理解和运用模式匹配。
基础模式匹配习题
习题1:正则表达式匹配电子邮件地址
任务描述: 编写一个正则表达式,用于匹配有效的电子邮件地址。
代码示例:
import re
def match_email(email):
pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
return re.match(pattern, email) is not None
# 测试
print(match_email("example@example.com")) # 应输出 True
print(match_email("example@.com")) # 应输出 False
习题2:Python字符串模式匹配
任务描述: 使用Python的字符串方法find()来查找子字符串。
代码示例:
def find_substring(string, substring):
return string.find(substring) != -1
# 测试
print(find_substring("hello world", "world")) # 应输出 True
print(find_substring("hello world", "worlds")) # 应输出 False
中级模式匹配习题
习题3:正则表达式中的捕获组
任务描述: 使用正则表达式提取电子邮件地址中的用户名和域名。
代码示例:
import re
def extract_email_parts(email):
pattern = r'([a-zA-Z0-9._%+-]+)@([a-zA-Z0-9.-]+\.[a-zA-Z]{2,})'
match = re.match(pattern, email)
if match:
return match.group(1), match.group(2)
return None, None
# 测试
username, domain = extract_email_parts("user@example.com")
print(username, domain) # 应输出 user example.com
习题4:使用Python的re模块进行复杂匹配
任务描述: 使用正则表达式匹配电话号码格式,如“123-456-7890”或“123.456.7890”。
代码示例:
import re
def match_phone_number(phone_number):
pattern = r'^(\d{3})[-.]?(\d{3})[-.]?(\d{4})$'
return re.match(pattern, phone_number) is not None
# 测试
print(match_phone_number("123-456-7890")) # 应输出 True
print(match_phone_number("123.456.7890")) # 应输出 True
print(match_phone_number("1234567890")) # 应输出 False
高级模式匹配习题
习题5:递归模式匹配
任务描述: 编写一个递归函数,用于匹配字符串中的所有括号匹配。
代码示例:
def match_parentheses(s):
stack = []
for char in s:
if char == '(':
stack.append(char)
elif char == ')':
if stack and stack[-1] == '(':
stack.pop()
else:
return False
return len(stack) == 0
# 测试
print(match_parentheses("(hello)")) # 应输出 True
print(match_parentheses("((hello))")) # 应输出 True
print(match_parentheses("(hello")) # 应输出 False
习题6:多模式匹配与优先级
任务描述: 使用正则表达式匹配IP地址,同时确保域名部分不包含数字。
代码示例:
import re
def match_ip_address(ip_address):
pattern = r'^(\d{1,3}\.){3}\d{1,3}@[a-zA-Z-]+\.[a-zA-Z]{2,}$'
return re.match(pattern, ip_address) is not None
# 测试
print(match_ip_address("192.168.1.1@example.com")) # 应输出 True
print(match_ip_address("192.168.1.1@123example.com")) # 应输出 False
通过这些习题,你可以逐步提高自己在模式匹配方面的技能。记住,多练习是提高的关键,尝试自己解决更多实际问题,将所学知识应用到实践中。
