萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> HTML 腳本教學

Python 正則 re.match vs re.search 區別詳解與實戰選型

核心區別

方法匹配範圍行為相當於
re.match(pattern, string)僅字符串開頭從索引 0 開始匹配Perl m/^pattern/
re.search(pattern, string)字符串任意位置掃描整串直到首次匹配Perl m/pattern/ (默認)

代碼演示

import re

text = "helloworld, i am 30 !"

# search: 找到 "world" 於位置 5
m1 = re.search("world", text)
print(m1.group())  # world

# match: 開頭不是 "world",失敗
m2 = re.match("world", text)
print(m2)  # None

# match: 開頭匹配 "helloworld"
m3 = re.match("helloworld", text)
print(m3.group())  # helloworld

何時用哪個?

  • 驗證開頭格式(如協議頭、前綴):用 match — re.match(r'https?://', url)
  • 提取任意位置內容(如解析日誌、查找關鍵字):用 search
  • 需匹配整串:match + 結尾 $,或 fullmatch (Py3.4+)

進階:預編譯與 Flags

# 預編譯提升性能
PATTERN = re.compile(r'\d{4}-\d{2}-\d{2}')

# 多行模式:^/$ 匹配每行開頭結尾
re.search(r'^ERROR', log, re.MULTILINE)

# 忽略大小寫
re.match(r'hello', text, re.IGNORECASE)

MatchObject 常用屬性/方法

m = re.search(r'(\w+)@(\w+\.\w+)', 'mail: test@example.com')
m.group()      # 'test@example.com' (整個匹配)
m.group(1)     # 'test' (第1組)
m.group(2)     # 'example.com'
m.groups()     # ('test', 'example.com')
m.start()      # 6
m.end()        # 22
m.span()       # (6, 22)
copyright © 萬盛學電腦網 all rights reserved