re.fullmatch Validates The Entire String
re.fullmatch requires the pattern to cover the entire string; match and search only anchor the start, so trailing garbage slips past validation.
Code
import re
HEX_COLOR = re.compile(r"#[0-9a-fA-F]{6}")
SLUG = re.compile(r"[a-z0-9]+(?:-[a-z0-9]+)*")
payloads = ["#1a2b3c", "#12345", " #ffffff", "deep-dive-post", "-not-ok", "blog/post"]
for value in payloads:
# fullmatch 要求整个字符串都匹配:校验输入时不要用 search/match
color_ok = HEX_COLOR.fullmatch(value) is not None
slug_ok = SLUG.fullmatch(value) is not None
print(f"{value!r:18} hex_color={color_ok!s:6} slug={slug_ok!s:6}")
# 对照:match 只锚定开头,拖尾字符照样放行;fullmatch 直接拒绝
print("match admits trailer:", HEX_COLOR.match("#1a2b3c;DROP") is not None)
print("fullmatch rejects trailer:", HEX_COLOR.fullmatch("#1a2b3c;DROP") is not None)Output
Captured from a sandboxed run of this snippet in the build pipeline.
'#1a2b3c' hex_color=True slug=False
'#12345' hex_color=False slug=False
' #ffffff' hex_color=False slug=False
'deep-dive-post' hex_color=False slug=True
'-not-ok' hex_color=False slug=False
'blog/post' hex_color=False slug=False
match admits trailer: True
fullmatch rejects trailer: FalseWhat the code does
The file repeats itself only inside for value in payloads.
Module-level bindings hold the data — payloads — with no function scope in between.
Taking the usage further
The demo output is labeled (match admits trailer:, fullmatch rejects trailer:), so every printed line maps back to its originating operation.
Interactive Tools for This Topic
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.Regular Expression TesterTest regular expressions against sample text with live match highlighting, capture group extraction, and flags support for global, case-insensitive, and multiline modes.
FAQ
- Which packages does this snippet need?
- None. Every symbol the code uses resolves inside the standard library. Its state lives in module-level bindings: `payloads`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.