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.

PythonForm Validation

Code

pythonsnippet
16 lines
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: False

What 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

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`.