在Python中,re模块提供了对正则表达式的支持。你可以使用re.search()、re.findall()等函数来查找字符串中与正则表达式匹配的部分。
下面是一些示例:
使用re.search()查找字符串中与正则表达式匹配的第一个子串:import retext = "Hello, my phone number is 123-456-7890."pattern = r'\d{3}-\d{3}-\d{4}'match = re.search(pattern, text)if match: print("Found a match:", match.group())else: print("No match found.")使用re.findall()查找字符串中与正则表达式匹配的所有子串:import retext = "Hello, my phone numbers are 123-456-7890 and 987-654-3210."pattern = r'\d{3}-\d{3}-\d{4}'matches = re.findall(pattern, text)if matches: print("Found matches:", matches)else: print("No matches found.")使用re.sub()替换字符串中与正则表达式匹配的子串:import retext = "Hello, my phone number is 123-456-7890."pattern = r'\d{3}-\d{3}-\d{4}'replacement = "XXX-XXX-XXXX"new_text = re.sub(pattern, replacement, text)print("New text:", new_text)这些示例展示了如何在Python中使用正则表达式进行查找和替换操作。你可以根据需要调整正则表达式以匹配不同的文本模式。


