"""Offline SQLite verifier for MySQL Chapter 22: REGEXP / RLIKE pattern matching."""
import json
import re
import sqlite3
import sys
def make_case(name: str, summary: str, expected, actual) -> dict:
return {
"name": name,
"summary": summary,
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def regexp_ci(pattern: str, value: str | None) -> int:
if value is None or pattern is None:
return 0
return 1 if re.search(pattern, str(value), re.IGNORECASE) else 0
def regexp_cs(pattern: str, value: str | None) -> int:
if value is None or pattern is None:
return 0
return 1 if re.search(pattern, str(value)) else 0
def main() -> None:
conn = sqlite3.connect(":memory:")
conn.create_function("REGEXP", 2, regexp_ci)
conn.create_function("REGEXP_CS", 2, regexp_cs)
cur = conn.cursor()
cur.executescript(
"""
CREATE TABLE person_tbl (name TEXT);
INSERT INTO person_tbl VALUES
('steve'), ('stanley'), ('brook'), ('omar'),
('alice'), ('smart'), ('echo'), ('cook');
CREATE TABLE orders (id INT, order_description TEXT);
INSERT INTO orders VALUES
(1, 'batch item42 shipped'),
(2, 'single item without number'),
(3, 'item9 pending');
CREATE TABLE products (id INT, product_name TEXT);
INSERT INTO products VALUES
(1, 'apple juice'),
(2, 'Apple Watch'),
(3, '90W Charger'),
(4, '2026 Calendar'),
(5, 'USB Hub');
CREATE TABLE employees (id INT, last_name TEXT);
INSERT INTO employees VALUES
(1, 'Smith'), (2, 'Johnson'), (3, 'Brown'), (4, 'Williams');
"""
)
# 1. Anchors ^, $, substring, and combined alternation
starts_st = [
r[0]
for r in cur.execute(
"SELECT name FROM person_tbl WHERE name REGEXP '^st' ORDER BY name"
).fetchall()
]
ends_ok = [
r[0]
for r in cur.execute(
"SELECT name FROM person_tbl WHERE name REGEXP 'ok$' ORDER BY name"
).fetchall()
]
contains_mar = [
r[0]
for r in cur.execute(
"SELECT name FROM person_tbl WHERE name REGEXP 'mar' ORDER BY name"
).fetchall()
]
vowel_or_ok = [
r[0]
for r in cur.execute(
"SELECT name FROM person_tbl WHERE name REGEXP '^[aeiou]|ok$' ORDER BY name"
).fetchall()
]
case1 = make_case(
"regexp_anchors_and_substrings",
"Verify ^st, ok$, mar, and ^[aeiou]|ok$ patterns with SQLite REGEXP hook",
{
"starts_st": ["stanley", "steve"],
"ends_ok": ["brook", "cook"],
"contains_mar": ["omar", "smart"],
"vowel_or_ok": ["alice", "brook", "cook", "echo", "omar"],
},
{
"starts_st": starts_st,
"ends_ok": ends_ok,
"contains_mar": contains_mar,
"vowel_or_ok": vowel_or_ok,
},
)
# 2. Character classes, quantifiers *, +, ?, {n}, {n,m}, \w, \s
item_digits = [
r[0]
for r in cur.execute(
"SELECT id FROM orders WHERE order_description REGEXP 'item[0-9]+' ORDER BY id"
).fetchall()
]
starts_digit = [
r[0]
for r in cur.execute(
"SELECT product_name FROM products WHERE product_name REGEXP '^[0-9]' ORDER BY id"
).fetchall()
]
quant_checks = {
"dot": bool(re.search("a.c", "abc")),
"char_set": bool(re.search("[abc]", "plain")),
"neg_set": bool(re.search("[^abc]", "plain")),
"star_zero": bool(re.search("zo*", "z")),
"plus_one": [bool(re.search("zo+", "z")), bool(re.search("zo+", "zoo"))],
"optional_q": [bool(re.search("colou?r", "color")), bool(re.search("colou?r", "colour"))],
"exact_n": [bool(re.search("o{2}", "Bob")), bool(re.search("o{2}", "food"))],
"range_nm": [bool(re.search("^a{2,3}$", "a")), bool(re.search("^a{2,3}$", "aa")), bool(re.search("^a{2,3}$", "aaaa"))],
"word_space": bool(re.search(r"^\w+\s\w+$", "hello world")),
}
case2 = make_case(
"regexp_char_classes_and_quantifiers",
"Verify character classes ([abc], [^abc], [0-9], \\w, \\s) and quantifiers (*, +, ?, {n}, {n,m})",
{
"item_digits": [1, 3],
"starts_digit": ["90W Charger", "2026 Calendar"],
"quant_checks": {
"dot": True,
"char_set": True,
"neg_set": True,
"star_zero": True,
"plus_one": [False, True],
"optional_q": [True, True],
"exact_n": [False, True],
"range_nm": [False, True, False],
"word_space": True,
},
},
{
"item_digits": item_digits,
"starts_digit": starts_digit,
"quant_checks": quant_checks,
},
)
# 3. Case-insensitive default vs case-sensitive (MySQL REGEXP BINARY / REGEXP_LIKE 'c')
ci_matches = [
r[0]
for r in cur.execute(
"SELECT product_name FROM products WHERE product_name REGEXP 'apple' ORDER BY id"
).fetchall()
]
cs_matches = [
r[0]
for r in cur.execute(
"SELECT product_name FROM products WHERE REGEXP_CS('apple', product_name) = 1 ORDER BY id"
).fetchall()
]
case3 = make_case(
"regexp_case_sensitive_binary",
"Verify case-insensitive default vs case-sensitive (BINARY) regex matching on products",
{
"case_insensitive": ["apple juice", "Apple Watch"],
"case_sensitive": ["apple juice"],
},
{
"case_insensitive": ci_matches,
"case_sensitive": cs_matches,
},
)
# 4. Alternation p1|p2|p3 and grouping
emp_or = [
r[0]
for r in cur.execute(
"SELECT last_name FROM employees WHERE last_name REGEXP 'Smith|Johnson' ORDER BY id"
).fetchall()
]
group_alt = [bool(re.search("(z|f)ood", s)) for s in ("zood", "food", "mood")]
case4 = make_case(
"regexp_alternation_and_rlike_equiv",
"Verify alternation (Smith|Johnson, (z|f)ood) used identically by REGEXP and RLIKE",
{
"employees": ["Smith", "Johnson"],
"group_alt": [True, True, False],
},
{
"employees": emp_or,
"group_alt": group_alt,
},
)
conn.close()
payload = {
"version": f"CPython {sys.version.split()[0]} / SQLite {sqlite3.sqlite_version} (offline MySQL verifier)",
"cases": [case1, case2, case3, case4],
}
print(json.dumps(payload, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
本例需在 Windows x64、CPython 3.12.14、内置 sqlite3(SQLite 3.53.1)本地离线关系语义验证环境(全程内存库或临时目录运行,未连接外部 MySQL 服务端)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14、内置 sqlite3(SQLite 3.53.1)本地离线关系语义验证环境(全程内存库或临时目录运行,未连接外部 MySQL 服务端)。
入口文件:projects/mysql-regexp-lab/explore-regexp.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-regexp.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、内置 sqlite3(SQLite 3.53.1)本地离线关系语义验证环境(全程内存库或临时目录运行,未连接外部 MySQL 服务端)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联41章) · 含当前章节或实例 · mbskycom202612a1590.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1619.zip