让我们通过示例来了解一下 python re 模块中的两个方法 re.sub() 和 re.match()。
re.sub() 函数用于替换字符串中模式的出现。它需要三个主要参数:
re.sub(pattern, replacement, string, count=0, flags=0)
让我们用单词 num 替换字符串中的所有数字。
import re text = "the price is 123 dollars and 45 cents." new_text = re.sub(r'd+', 'num', text) print(new_text)
输出:
the price is num dollars and num cents.
这里,d+ 是匹配一个或多个数字的正则表达式模式。 re.sub() 函数用字符串“num”替换此模式的所有出现。
re.match() 函数仅检查字符串开头的匹配。如果在字符串的开头找到匹配项,则返回一个匹配对象。否则,它返回 none。
re.match(pattern, string, flags=0)
让我们检查一个字符串是否以单词开头,后跟数字。
import re text = "price123 is the total cost." match = re.match(r'w+d+', text) if match: print(f"matched: {match.group()}") else: print("no match found")
输出:
matched: price123
这里,w+匹配一个或多个单词字符(字母、数字和下划线),d+匹配一个或多个数字。由于字符串以“price123”开头,因此成功匹配并打印它。
您想要更多示例或更深入地了解正则表达式吗?
让我们通过更高级的示例和正则表达式 (regex) 模式的解释来更深入地了解 re.sub() 和 re.match()。
假设我们想通过替换电话号码的格式来格式化电话号码。我们有 123-456-7890 等电话号码,我们希望将其替换为 (123) 456-7890 等格式。
import re text = "contact me at 123-456-7890 or 987-654-3210." formatted_text = re.sub(r'(d{3})-(d{3})-(d{4})', r'(1) 2-3', text) print(formatted_text)
说明:
输出:
contact me at (123) 456-7890 or (987) 654-3210.
现在让我们看看如何将 re.match() 与更复杂的模式一起使用。假设您想要验证给定字符串是否是有效的电子邮件地址,但我们只想检查它是否以电子邮件格式开头。
import re email = "someone@example.com sent you a message." # basic email pattern matching the start of a string pattern = r'^[a-za-z0-9_.+-]+@[a-za-z0-9-]+.[a-za-z0-9-.]+' match = re.match(pattern, email) if match: print(f"valid email found: {match.group()}") else: print("no valid email at the start")
说明:
此模式将匹配字符串开头的有效电子邮件地址。
输出:
valid email found: someone@example.com
如果您想要更多动态行为,您还可以使用函数作为 re.sub() 中的替代品。让我们看看如何。
import re text = "this is a test sentence." def capitalize(match): return match.group(0).capitalize() new_text = re.sub(r'bw+b', capitalize, text) print(new_text)
说明:
输出:
this is a test sentence.
如果你想在字符串中任何地方搜索模式(不仅仅是在开头),你应该使用re.search()而不是re.match()。
import re text = "this is my email someone@example.com" # search for an email pattern anywhere in the string pattern = r'[a-za-z0-9_.+-]+@[a-za-z0-9-]+.[a-za-z0-9-.]+' search = re.search(pattern, text) if search: print(f"email found: {search.group()}") else: print("no email found")
输出:
Email found: someone@example.com
这里,re.search() 会在字符串中的任意位置查找模式,这与 re.match() 不同,re.match() 只检查开头。
这些示例应该可以让您更全面地了解正则表达式在 python 中的工作原理!您想进一步探索任何特定模式或问题吗?