re.match Anchors, re.search Scans

re.match anchors at string start while re.search scans for the first hit; the two agree only when the pattern pins to position zero.

PythonForm Validation

Code

pythonsnippet
17 lines
import re

pattern = re.compile(r"SKU-(\d{4})")

# re.match 只从字符串开头尝试:适合“必须以此开头”的校验(anchor)
print("match:", bool(re.match(pattern, "SKU-0042")))
print("match mid-text:", re.match(pattern, "see SKU-0042"))

# re.search 扫描全文并返回第一处命中(scan)
hit = re.search(pattern, "order see SKU-0042 and SKU-0007")
print("search:", hit.group(0), "| digits:", hit.group(1), "| start:", hit.start())

# search 找不到返回 None;match 失败也返回 None,但扫描范围不同
print("search miss:", re.search(pattern, "no codes here"))

# findall 一次取齐所有匹配;search 只给第一个
print("findall:", re.findall(pattern, "SKU-0001 x SKU-0002"))

Output

Captured from a sandboxed run of this snippet in the build pipeline.

match: True
match mid-text: None
search: SKU-0042 | digits: 0042 | start: 10
search miss: None
findall: ['0001', '0002']

What the code does

Demo state sits in top-level bindings: pattern, hit.

Watch out for

  • Every call is a built-in — nothing enters from a supply chain.

Applying it

The run emits 5 labeled sections — match:, match mid-text:, search:, search miss:, findall: — one per step.

Interactive Tools for This Topic

FAQ

What does the package manager see?
An empty dependency file. The snippet imports nothing that needs fetching. Its state lives in module-level bindings: `pattern`, `hit`.