在Python中,match
关键字可以用于以下几个方面:
- 字符串匹配:使用
match
方法来检查一个字符串是否与指定的模式匹配。
import re pattern = r"Hello" string = "Hello, World!" result = re.match(pattern, string) if result: print("匹配成功") else: print("匹配失败")
- 正则表达式匹配:使用
re
模块的match
函数来进行正则表达式模式匹配。
import re pattern = r"Hello" string = "Hello, World!" result = re.match(pattern, string) if result: print("匹配成功") else: print("匹配失败")
- 模式匹配:使用
match
语句来对多个模式进行匹配,并执行相应的代码块。
value = https://www.yisu.com/ask/2"匹配到1") case 2: print("匹配到2") case _: print("未匹配到")
需要注意的是,模式匹配是在Python 3.10及以上版本中引入的新特性。