蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

离线验证 $regex 区分/忽略大小写、数组元素匹配、^前缀锚定与安全元字符转义

PYTHONWindows x64、CPython 3.12.14 离线文档/管道/索引/GridFS/ObjectId 验证环境(本地未安装 mongod/mongosh 服务端)。explore-regular-expression.py
explore-regular-expression.py91 行
"""Offline MongoDB $regex, $options:'i', array matching & prefix optimization verifier."""
import json
import re

VERSION = "CPython 3.12.14 offline MongoDB document/query verifier (mongod absent)"


def regex_find(docs, field, pattern, options=""):
    flags = 0
    if "i" in options:
        flags |= re.IGNORECASE
    if "m" in options:
        flags |= re.MULTILINE
    if "s" in options:
        flags |= re.DOTALL
    compiled = re.compile(pattern, flags)
    matched = []
    for d in docs:
        val = d.get(field)
        if isinstance(val, list):
            if any(isinstance(el, str) and compiled.search(el) for el in val):
                matched.append(d)
        elif isinstance(val, str) and compiled.search(val):
            matched.append(d)
    return matched


def main():
    posts = [
        {"_id": 1, "post_text": "enjoy the mongodb articles on devhub", "tags": ["mongodb", "devhub"]},
        {"_id": 2, "post_text": "hey! this is my post on DevHub", "tags": ["DevHub", "tutorial"]},
        {"_id": 3, "post_text": "tut-01: prefix index optimization", "tags": ["tut", "perf"]},
    ]

    # Case 1: Case-sensitive $regex vs case-insensitive $options: "i"
    cs_hits = [d["_id"] for d in regex_find(posts, "post_text", "devhub")]
    ci_hits = [d["_id"] for d in regex_find(posts, "post_text", "devhub", options="i")]
    c1_actual = {"case_sensitive_ids": cs_hits, "case_insensitive_ids": ci_hits}
    c1_expected = {"case_sensitive_ids": [1], "case_insensitive_ids": [1, 2]}

    # Case 2: Regex matching inside array field (`tags`)
    arr_hits = [d["_id"] for d in regex_find(posts, "tags", "dev", options="i")]
    c2_actual = {"matched_array_doc_ids": arr_hits}
    c2_expected = {"matched_array_doc_ids": [1, 2]}

    # Case 3: Prefix regex (^tut) indexability & safe dynamic variable escaping (no eval)
    user_input = "tut-01"
    safe_pattern = f"^{re.escape(user_input)}"
    prefix_hits = [d["_id"] for d in regex_find(posts, "post_text", safe_pattern)]
    # Compare against unescaped metacharacter input (e.g. "c++")
    escaped_cpp = re.escape("c++")
    c3_actual = {
        "prefix_anchored": safe_pattern.startswith("^"),
        "prefix_hits": prefix_hits,
        "safe_escaped_cpp": escaped_cpp,
    }
    c3_expected = {
        "prefix_anchored": True,
        "prefix_hits": [3],
        "safe_escaped_cpp": r"c\+\+",
    }

    cases = [
        {
            "name": "regex_case_sensitive_vs_options_i",
            "summary": "Verify $regex matches exact case by default and matches mixed case with $options: 'i'.",
            "expected": c1_expected,
            "actual": c1_actual,
            "passed": c1_actual == c1_expected,
        },
        {
            "name": "regex_array_element_matching",
            "summary": "Verify $regex matches when any string element in the tags array satisfies the pattern.",
            "expected": c2_expected,
            "actual": c2_actual,
            "passed": c2_actual == c2_expected,
        },
        {
            "name": "regex_prefix_optimization_and_safe_escape",
            "summary": "Verify anchored ^prefix pattern and safe regex escaping for dynamic variables without eval().",
            "expected": c3_expected,
            "actual": c3_actual,
            "passed": c3_actual == c3_expected,
        },
    ]
    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
本例需在 Windows x64、CPython 3.12.14 离线文档/管道/索引/GridFS/ObjectId 验证环境(本地未安装 mongod/mongosh 服务端)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、CPython 3.12.14 离线文档/管道/索引/GridFS/ObjectId 验证环境(本地未安装 mongod/mongosh 服务端)。

入口文件:projects/mongodb-regular-expression-lab/explore-regular-expression.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-regular-expression.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14 离线文档/管道/索引/GridFS/ObjectId 验证环境(本地未安装 mongod/mongosh 服务端)。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:MongoDB

课程关联工程包(登记关联49章) · 含当前章节或实例 · mbskycom202612a1732.zip

下载课程关联工程包:MongoDB

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1764.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习