import json
def report(name, value):
print(json.dumps([name, value], ensure_ascii=True))
def error_name(action):
try:
action()
except (AttributeError, IndexError, KeyError, NameError, TypeError, ValueError) as error:
return type(error).__name__
return None
import locale
import re
def match_text(match):
return None if match is None else match.group()
def span(match):
return None if match is None else match.span()
def capture_error(action):
try:
action()
except (re.error, IndexError, TypeError, ValueError) as exc:
return type(exc).__name__
return None
def search_cases():
text = "port=7; gate=12"
pattern = r"([a-z]+)=(\d+)"
matched = re.match(pattern, text)
searched = re.search(pattern, "!" + text)
optional = re.match(r"(?P<zone>[A-Z]+)(?:-(\d+))?", "A")
report("match_args", {
"pattern": [span(re.match("port", text)), span(re.match(r"por.", text))],
"string": [span(re.match(b"port", text.encode())), capture_error(lambda: re.match(b"port", text))],
"flags": [span(re.match("PORT", text)), span(re.match("PORT", text, re.I))],
})
report("match_groups", {
"group": [matched.group(0), matched.group(2, 1), optional.group("zone"), optional.group(2)],
"groups": [matched.groups(), optional.groups("unset"), re.match("p", text).groups()],
})
report("search_args", {
"pattern": [span(re.search("gate", text)), span(re.search(r"gat.", text))],
"string": [span(re.search("gate", "!" + text)), capture_error(lambda: re.search("gate", b"gate"))],
"flags": [span(re.search("^GATE", "note\ngate=12")), span(re.search("^GATE", "note\ngate=12", re.I | re.M))],
})
report("search_groups", {
"group": [searched.group(), searched.group(1, 2), capture_error(lambda: searched.group(3))],
"groups": [searched.groups(), re.search(r"([A-Z]+)(\d+)?", "!A").groups("empty")],
})
report("match_position", [span(re.match("port", text)), span(re.match("gate", text))])
report("match_capture", [matched.group(), matched.group(1), matched.group(2), match_text(re.match(pattern, "!"))])
report("search_position", [span(re.search("port", text)), span(re.search("gate", text))])
report("search_capture", [searched.group(), searched.group(1), searched.group(2), match_text(re.search(pattern, "!"))])
report("match_vs_search", [match_text(re.match("GATE", text, re.I | re.M)),
match_text(re.search("GATE", text, re.I | re.M)),
match_text(re.fullmatch("gate", "gate!")),
match_text(re.fullmatch("gate", "gate"))])
target = "ab37cd90"
compiled = re.compile(r"\d+")
inside = compiled.match(target, 2, 4)
report("compiled_bounds", [type(compiled).__name__, span(compiled.match(target)),
span(compiled.match(target, 1, 4)), inside.group(),
inside.start(), inside.end(), inside.span(),
span(compiled.search(target, 3, 4)),
span(re.compile(r"^37").search(target, 2, 4)),
span(re.compile(r"^37").search(target[2:4]))])
report("capture_positions", [optional.group(), optional.group(0), optional.group(1, 2),
optional.start(), optional.end(), optional.span(),
optional.start("zone"), optional.end("zone"), optional.span("zone"),
optional.span(2), capture_error(lambda: optional.group(3))])
def extraction_cases():
pattern = r"(\d+)"
raw = "A3 B24 C7"
compiled = re.compile(r"\d+")
report("findall_results", [compiled.findall(raw), compiled.findall(raw, 2, 5),
re.findall(pattern, raw), re.findall(r"([A-Z])(\d+)", raw),
re.findall(r"([A-Z])(\d+)?", "D F9"), re.findall(r"\d+", "none")])
iterator = re.finditer(pattern, raw)
first = next(iterator)
report("finditer_results", [iter(iterator) is iterator, [first.group(), first.span()],
[[match.group(), match.span()] for match in iterator], list(iterator)])
report("finditer_args", {
"pattern": [[m.group() for m in re.finditer(r"\d", "id17")],
[m.group() for m in re.finditer(r"\d+", "id17")]],
"string": [[m.span() for m in re.finditer("id", "id ID id")],
capture_error(lambda: list(re.finditer(b"id", "id")))],
"flags": [[m.span() for m in re.finditer("ID", "id ID")],
[m.span() for m in re.finditer("ID", "id ID", re.I)]],
})
report("split_args", {
"pattern": [re.split(r"[,;]", "a,b;c"), re.split(r"([,;])", "a,b;c")],
"string": [re.split(r"\W+", ",alpha;beta."), capture_error(lambda: re.split(b",", "a,b"))],
"maxsplit": [re.split(",", "a,b,c"), re.split(",", "a,b,c", maxsplit=1)],
"flags": [re.split("x", "aXbxc"), re.split("x", "aXbxc", flags=re.I)],
})
report("split_results", [re.split(r"\W+", "alpha, beta."),
re.split(r"(\W+)", " alpha, beta."),
re.split(r"\W+", " alpha, beta.", maxsplit=1),
re.split("a*", "dock"),
re.split("z+", "dock")])
note = "bay-35.2 # reading"
digits = r"(?P<num>\d+)"
callback_log = []
def double(match):
callback_log.append([match.group("num"), match.span()])
return str(2 * int(match.group("num")))
cleaned = re.sub(r"#.*$", "", note)
report("sub_text", [cleaned, re.sub(r"\D", "", cleaned), note, re.sub("bay", "dock", "BAY", flags=re.I)])
output = re.sub(digits, double, "S12T7")
report("sub_callback", [output, callback_log, re.subn(digits, r"[\g<num>]", "S12T7")])
report("sub_args", {
"pattern": [cleaned, re.sub(r"\D", "", cleaned)],
"repl": [re.sub(digits, r"[\g<num>]", "S12T7"), output],
"string": [note, cleaned],
"count": [re.sub(digits, "#", "S12T7", count=1), re.sub(digits, "#", "S12T7", count=0)],
})
def flags_cases():
previous = locale.setlocale(locale.LC_CTYPE)
try:
active = locale.setlocale(locale.LC_CTYPE, "C")
localized = [active, re.findall(rb"\w+", b"A_\xe9", re.L)[0].hex(),
re.search(rb"a", b"A", re.L | re.I).group().hex(),
capture_error(lambda: re.compile(r"\w", re.L)),
capture_error(lambda: re.compile(rb"\w", re.A | re.L)),
bool(re.fullmatch(rb"\s", b"\v", re.L))]
finally:
locale.setlocale(locale.LC_CTYPE, previous)
report("flags", {
"re.I": [match_text(re.fullmatch("dock", "DOCK")), match_text(re.fullmatch("dock", "DOCK", re.I)),
match_text(re.fullmatch("[a-z]", "K", re.I)), match_text(re.fullmatch("[a-z]", "K", re.I | re.A))],
"re.L": localized,
"re.M": [re.findall(r"^dock$", "note\ndock\nend"), re.findall(r"^dock$", "note\ndock\nend", re.M),
span(re.match(r"^dock", "note\ndock", re.M))],
"re.S": [match_text(re.fullmatch("a.b", "a\nb")), match_text(re.fullmatch("a.b", "a\nb", re.S))],
"re.U": [re.findall(r"\w", "雪A_!"), re.findall(r"\w", "雪A_!", re.U),
re.findall(r"\w", "雪A_!", re.A), capture_error(lambda: re.compile(rb"\w", re.U))],
"re.X": [match_text(re.fullmatch("a # join\n [ ] b", "a b", re.X)),
match_text(re.fullmatch(r"a\ b", "a b", re.X)),
capture_error(lambda: re.compile("(? :a)", re.X))],
})
def syntax_cases():
contiguous = re.compile(r"[A-Z]\d")
line = "Q1R2 gap S3"
position, tokens = 0, []
while (match := contiguous.match(line, position)) is not None:
tokens.append(match.group())
position = match.end()
digit_sample = "2٣②x"
word_sample = "雪_A-7"
spaces = "A\t\u00a0B"
limits = [match_text(re.fullmatch(r"x{2,4}", value)) for value in ("x", "xx", "xxxx", "xxxxx")]
report("syntax", {
"^": [span(re.search("^dock", "note\ndock")), span(re.search("^dock", "note\ndock", re.M))],
"$": [span(re.search("dock$", "dock\n")), span(re.search(r"dock\Z", "dock\n"))],
".": [re.findall(".", "a\nb"), re.findall(".", "a\nb", re.S)],
"[...]": re.findall("[pqr]", "map, rag"),
"[^...]": re.findall("[^xy]", "x-yZ"),
"*": [match_text(re.fullmatch("q*z", "z")), match_text(re.fullmatch("q*z", "qqz"))],
"+": [match_text(re.fullmatch("q+z", "z")), match_text(re.fullmatch("q+z", "qqz"))],
"?": [match_text(re.match("a?", "a")), match_text(re.match("a??", "a")), match_text(re.fullmatch("a?b", "b"))],
"{n}": [match_text(re.fullmatch("x{2}", "xx")), match_text(re.fullmatch("x{2}", "xxx"))],
"{n,}": [match_text(re.fullmatch("x{2,}", "xxxx")), match_text(re.fullmatch("x{2,}", "x"))],
"{n,m}": limits,
"a|b": [match_text(re.search("do|dock", "dock")), match_text(re.search("dock|do", "dock"))],
"(...)": re.fullmatch(r"([a-z]+):(\d+)", "bay:7").groups(),
"(?imx)": [span(re.search("(?imx) ^ DOCK $", "note\ndock")),
capture_error(lambda: re.compile("a(?i)b"))],
"(?-imx)": capture_error(lambda: re.compile("(?-imx)")),
"(?:...)": [re.fullmatch("(?:ab)+(c)", "ababc").groups(), re.compile("(?:ab)+(c)").groups],
"(?imx:...)": [match_text(re.fullmatch("(?i:ab)c", "ABc")), match_text(re.fullmatch("(?i:ab)c", "ABC"))],
"(?-imx:...)": [match_text(re.fullmatch("(?i)a(?-i:b)c", "AbC")), match_text(re.fullmatch("(?i)a(?-i:b)c", "ABC"))],
"(?#...)": match_text(re.fullmatch("a(?# label)b", "ab")),
"(?=...)": [span(re.search(r"bay(?=:)", "bay:7")), span(re.search(r"bay(?=:)", "bay7"))],
"(?!...)": [span(re.search(r"bay(?!:)", "bay7")), span(re.search(r"bay(?!:)", "bay:7"))],
"(?>...)": [match_text(re.fullmatch("(?:ab|a)b", "ab")), match_text(re.fullmatch("(?>ab|a)b", "ab"))],
r"\w": [re.findall(r"\w", word_sample), re.findall(r"\w", word_sample, re.A)],
r"\W": [re.findall(r"\W", word_sample), re.findall(r"\W", word_sample, re.A)],
r"\s": [re.findall(r"\s", spaces), re.findall(r"\s", spaces, re.A)],
r"\S": [re.findall(r"\S", spaces), re.findall(r"\S", spaces, re.A)],
r"\d": [re.findall(r"\d", digit_sample), re.findall(r"\d", digit_sample, re.A)],
r"\D": [re.findall(r"\D", digit_sample), re.findall(r"\D", digit_sample, re.A)],
r"\A": [span(re.search(r"\Adock", "dock\n")), span(re.search(r"\Adock", "note\ndock", re.M)),
span(re.compile(r"\Adock").search("!dock", 1))],
r"\Z": [span(re.search(r"dock\Z", "dock")), span(re.search(r"dock\Z", "dock\n"))],
r"\z": capture_error(lambda: re.compile(r"\z")),
r"\G": [capture_error(lambda: re.compile(r"\G")), tokens, position],
r"\b": [span(re.search(r"ay\b", "bay!")), span(re.search(r"ay\b", "bayou")), match_text(re.fullmatch(r"[\b]", "\b"))],
r"\B": [span(re.search(r"ay\B", "bayou")), span(re.search(r"ay\B", "bay!")), span(re.search(r"\B", ""))],
"换行与制表": [len(r"\n"), len("\n"), re.findall(r"\n|\t", "a\tb\n")],
r"\1–\9": [match_text(re.fullmatch(r"([A-Z])\1", "QQ")), match_text(re.fullmatch(r"([A-Z])\1", "QR"))],
r"\10": [match_text(re.fullmatch(r"(a)(b)(c)(d)(e)(f)(g)(h)(i)(j)\10", "abcdefghijj")),
capture_error(lambda: re.compile(r"(a)\10")), match_text(re.fullmatch(r"\010", "\b")),
re.sub(r"(a)", r"\g<1>0", "a")],
})
report("literal", {"字面词": [match_text(re.search("berth", "near berth")),
match_text(re.fullmatch(re.escape("a.b"), "a.b")),
match_text(re.fullmatch(re.escape("a.b"), "axb"))]})
report("classes", {
"[Aa]lpha": [match_text(re.fullmatch("[Aa]lpha", x)) for x in ("Alpha", "alpha", "ALPHA")],
"doc[ks]": [match_text(re.fullmatch("doc[ks]", x)) for x in ("dock", "docs", "doc")],
"[aeiou]": re.findall("[aeiou]", "loadout"),
"[0-9]": re.findall("[0-9]", digit_sample),
"[a-z]": re.findall("[a-z]", "aZö7"),
"[A-Z]": re.findall("[A-Z]", "aZÖ7"),
"[a-zA-Z0-9]": re.findall("[a-zA-Z0-9]", "aZ_雪7"),
"[^aeiou]": re.findall("[^aeiou]", "aB!\n"),
"[^0-9]": re.findall("[^0-9]", digit_sample),
})
report("special", {
".": [re.findall(r"[.\n]", "a.\n"), re.findall(r"(?s:.)", "a.\n")],
r"\d": re.findall(r"\d", digit_sample),
r"\D": re.findall(r"\D", digit_sample),
r"\s": re.findall(r"\s", spaces),
r"\S": re.findall(r"\S", spaces),
r"\w": re.findall(r"\w", word_sample),
r"\W": re.findall(r"\W", word_sample),
})
if __name__ == "__main__":
search_cases()
extraction_cases()
flags_cases()
syntax_cases()
本例需在 Windows CPython 3.12,标准库 re 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows CPython 3.12,标准库 re
入口文件:projects/python-legacy-lab/legacy-regex-lab.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
legacy-regex-lab.py,或下载右侧课程工程包。 - 确认本地已准备 Windows CPython 3.12,标准库 re。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联44章) · 含当前章节或实例 · mbskycom202611a446.zip