# ===== CodeLab: python-regex =====
# 以下代码片段按文章出现顺序拼接, 共 6 段

# ----- 片段 1 (python) -----
import re

text = "我的手机号是 13812345678,记得联系我"
m = re.search(r"1\d{10}", text)
if m:
    print("找到了:", m.group())

# ----- 片段 2 (python) -----
import re

text = "2026-08-07 19:52:30 ERROR 连接超时"

# search:在任意位置找第一处匹配
print(re.search(r"ERROR", text).group())          # ERROR

# findall:找出所有匹配,返回列表
print(re.findall(r"\d+", text))                   # ['2026', '08', '07', '19', '52', '30']

# sub:替换所有匹配
print(re.sub(r"\d{4}-\d{2}-\d{2}", "某日期", text))

# split:按匹配位置切分
print(re.split(r"[\s:]+", text))

# ----- 片段 3 (python) -----
import re

print(re.findall(r"\d+", "价格 99 元,原价 199 元"))        # ['99', '199']
print(re.search(r"\w+@\w+\.\w+", "联系 test@example.com").group())
print(bool(re.search(r"^Python", "Python 是最好的语言")))  # True,^ 锚定开头
print(bool(re.search(r"end$", "this is the end")))         # True,$ 锚定结尾

# ----- 片段 4 (python) -----
import re

log = "2026-08-07 19:52:30 ERROR 连接超时"
m = re.search(r"(\d{4}-\d{2}-\d{2})\s+(\d{2}:\d{2}:\d{2})\s+(\w+)", log)
print(m.group(1))   # 2026-08-07   日期
print(m.group(2))   # 19:52:30     时间
print(m.group(3))   # ERROR        级别

# 命名分组:用名字代替编号,可读性更好
m2 = re.search(r"(?P<date>\d{4}-\d{2}-\d{2})", log)
print(m2.group("date"))

# ----- 片段 5 (python) -----
import re

MOBILE = re.compile(r"^1[3-9]\d{9}$")
EMAIL = re.compile(r"^[\w.+-]+@[\w-]+\.[\w.-]+$")

def check_mobile(s: str) -> bool:
    return bool(MOBILE.match(s))

def check_email(s: str) -> bool:
    return bool(EMAIL.match(s))

print(check_mobile("13812345678"))     # True
print(check_mobile("23812345678"))     # False(2 开头)
print(check_mobile("1381234567"))      # False(少一位)
print(check_email("a.b+c@example.com"))  # True
print(check_email("a@b@c.com"))        # False

# ----- 片段 6 (python) -----
import re

html = "<b>加粗</b>和<i>斜体</i>"

# 贪心:一次吞到最后一个 >,结果只匹配到一整个大块
print(re.findall(r"<.*>", html))

# 非贪心:加 ? 变成"尽量少吃",逐个标签匹配
print(re.findall(r"<.*?>", html))

# finditer:大文本里逐个取匹配,避免一次生成大列表
for m in re.finditer(r"<.*?>", html):
    print(m.span(), m.group())
