re.escape Quotes User Input For Patterns

re.escape turns every metacharacter in untrusted text into a literal, so a dot searches for a dot instead of any character and composed templates stay exact.

PythonSecurity Boundaries

Code

pythonsnippet
20 lines
import re

# 用户输入里的元字符必须转义,否则 '.' 会匹配任意字符
query = "file.txt"
print("raw pattern   :", bool(re.search(re.escape(query), "file.txt backup")))

# 不转义的对照:'file.txt' 会命中 'filextxt' 这类意外文本
print("unescaped hit :", bool(re.search(query, "filextxt")))
print("escaped miss  :", bool(re.search(re.escape(query), "filextxt")))

# 混合模板:固定片段 + 转义后的用户输入
def find_literal(text: str, needle: str) -> bool:
    # needle 原样出现再跟一个叹号才算命中
    return re.search(re.escape(needle) + "!", text) is not None

print("exact 'v1.2!' :", find_literal("release v1.2! ready", "v1.2"))
print("regex 'v12!'  :", find_literal("release v12! ready", "v1.2"))

# escape 把所有元字符变成字面量:()[]{}*+?|^$ 全部加反斜杠
print("meta count    :", len(re.escape("[]{}()*+?|^$")), "chars after escaping 11")

Output

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

raw pattern   : True
unescaped hit : True
escaped miss  : False
exact 'v1.2!' : True
regex 'v12!'  : False
meta count    : 24 chars after escaping 11

What the code does

re.escape Quotes User Input For Patterns is built around the function find_literal.

Points of care

  • No install step: all APIs used ship with the platform.

Applying it

Signature: def find_literal(text: str, needle: str) -> bool

Each run prints the 6 labeled blocks raw pattern :, unescaped hit :, escaped miss :, exact, regex, meta count : in source order.

find_literal is the public entry point; everything else in the file exists to support it.

Statements that matter

def find_literal(text: str, needle: str) -> bool:
    # needle 原样出现再跟一个叹号才算命中
    return re.search(re.escape(needle) + "!", text) is not None

Interactive Tools for This Topic

FAQ

Does the runtime need any help from npm, pip, cargo, or the like?
No — the package manager has nothing to do here; nothing is declared. Every import resolves inside the standard library — `re`. The file defines `find_literal` at load time.