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("其他")

浙公網安備 33010602011771號