python命令search、match使用教程
1、search方法的语法
re.search(pattern,string,[flags=0])
- pattern 表示要匹配的正则表达式,
- string 表示要匹配的字符串
- flags为标志位,用于控制正则表达式的匹配方式,(如是否区分大小写,多行匹配等等,默认为0,代表无特殊匹配。)
- search方法是全字符串匹配的,匹配到第一个结果,即返回结果,不再继续。
- search方法匹配不到结果时,返回的是None,匹配到结果时,返回的是match对象。
- search方法匹配到结果时,使用match对象的group方法,获取匹配结果。
示例
import re pattern = r'\d+' # 匹配一个或多个数字 string = "There are 123 apples" match = re.search(pattern, string) if match: print("匹配的内容:", match.group()) print("匹配的位置:", match.start(), "到", match.end()) else: print("没有找到匹配的内容")
import re pattern = r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}' string = "请联系 support@example.com 或 sales@example.org" match = re.search(pattern, string) if match: print("找到的邮箱地址:", match.group()) else: print("没有找到邮箱地址")
match语句是python3.10中引入的新特性,其接受一个表达式并把它的值与一个或多个 case 块给出的一系列模式进行比较。这表面上像 C、Java 或 JavaScript等语言中的 switch 语句,但其实它更像 Rust 或 Haskell 中的模式匹配。只有第一个匹配的模式会被执行,并且它还可以提取值的组成部分(序列的元素或对象的属性)赋给变量。
基本语法:
match 变量: case 模式1: # 匹配模式1时执行的代码 case 模式2: # 匹配模式2时执行的代码 case _: # 默认分支,相当于 switch-case 中的 "default"
示例:
def http_status(code): match code: case 200: return "OK" case 400: return "Bad Request" case 404: return "Not Found" case _: return "Unknown Status" print(http_status(200)) # 输出: OK
匹配多种模式:
number = 5
match number:
case 1 | 3 | 5 | 7 | 9:
print("奇数")
case 2 | 4 | 6 | 8 | 10:
print("偶数")
case _:
print("其他")