【Python基础20讲】第17章:正则表达式
博主智算菩萨专注于人工智能、Python编程、音视频处理及UI窗体程序设计等方向。致力于以通俗易懂的方式拆解前沿技术从零基础入门到高阶实战陪伴开发者共同成长。目前已开设五大技术专栏累计发布多篇原创技术文章深受读者好评。 专栏导航人工智能前沿知识深度剖析Transformer架构、生成式AI、强化学习、具身智能、神经符号系统、大模型及智能体Agent技术系统性解析AI核心技术体系与前沿趋势。Python基础小白编程从零开始以保姆式教程讲解变量、数据类型、流程控制、函数等核心语法配有大量实战代码与避坑指南真正做到学以致用。机器学习与深度学习系统化拆解线性模型、决策树、随机森林、梯度提升树、神经网络等算法原理与工程实践覆盖从公式推导到代码实现的全链路内容。音频、图像与视频处理理论与实战涵盖FFmpeg多媒体处理、audio_shop开源工具、ComfyUI-WanVideoWrapper视频生成等实用技术从基础操作到高级应用一应俱全。UI窗体程序设计实战深入讲解UI设计、动态窗体生成、游戏UI框架设计等实战技巧提供从配置到编码的完整解决方案。智算菩萨以代码为经以算法为纬在人工智能的星辰大海中做你前行路上最可靠的导航者。17.1 正则表达式基础正则表达式Regular Expression是一种描述字符串模式的形式化语言。Python 的 re 模块提供了正则表达式的支持。常用函数re.search() 搜索第一个匹配re.match() 从开头匹配re.fullmatch() 完全匹配re.findall() 查找所有匹配。search 和 match 的区别match 只在字符串开头匹配search 在字符串任意位置搜索。findall 返回所有匹配的字符串列表如果模式中有分组则返回分组列表。17.2 正则表达式语法元字符. 匹配任意字符^ 匹配开头$ 匹配结尾* 匹配 0 次或多次 匹配 1 次或多次? 匹配 0 次或 1 次{n,m} 匹配 n 到 m 次[] 字符集| 或() 分组\ 转义。预定义字符类\d 数字、\w 单词字符、\s 空白字符、\b 单词边界。量词的贪婪/非贪婪模式*、、? 默认贪婪尽可能多匹配加 ? 变为非贪婪尽可能少匹配。17.3 分组与替换使用 () 创建捕获分组分组的内容可以通过 group(n) 访问。(?Ppattern) 创建命名分组。(?:pattern) 创建非捕获分组。re.sub(pattern, repl, string) 进行替换repl 可以是字符串或函数。re.split(pattern, string) 按模式分割字符串。re.compile(pattern) 预编译正则表达式提高重复使用的效率。匹配标志re.IGNORECASE 忽略大小写re.MULTILINE 多行模式re.DOTALL 使 . 匹配换行符。17.4 正则表达式实战技巧验证邮箱[\w.±][\w-].[\w.-]。验证手机号1[3-9]\d{9}。提取 HTML 标签内容(.*?)。匹配 IP 地址\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}。编写正则表达式的建议先明确需求再逐步构建模式使用 re.VERBOSE 模式添加注释提高可读性先用简单模式测试再逐步添加约束。正则表达式不是万能的——对于复杂的文本解析任务有时使用字符串方法或专门的解析库更合适。完整代码 第17章正则表达式 演示 re 模块、匹配模式、分组、替换、常用正则 importre# # 1. 基本匹配# print(*50)print( 基本匹配)print(*50)textPython 3.12 发布于 2023 年 10 月Python 2.7 已停止维护。# search: 搜索第一个匹配mre.search(rPython \d\.\d,text)print(fsearch:{m.group()ifmelseNone})# match: 从开头匹配mre.match(rPython,text)print(fmatch:{m.group()ifmelseNone})mre.match(r\d,text)print(fmatch 数字:{m.group()ifmelseNone})# fullmatch: 完全匹配mre.fullmatch(r\d,12345)print(ffullmatch:{m.group()ifmelseNone})# findall: 查找所有匹配resultsre.findall(rPython,text)print(ffindall Python:{results})resultsre.findall(r\d,text)print(ffindall 数字:{results})# finditer: 返回迭代器forminre.finditer(r\d\.\d,text):print(f finditer:{m.group()}at{m.span()})# # 2. 匹配模式标志# print(\n*50)print( 匹配模式)print(*50)textHello\nWorld\nPython# re.MULTILINE: ^ $ 匹配每行print(fMULTILINE ^\\w:{re.findall(r^\w,text,re.MULTILINE)})print(fMULTILINE \\w$:{re.findall(r\w$,text,re.MULTILINE)})# re.DOTALL: . 匹配换行符htmldiv\n Hello\n/divprint(fDOTALL:{re.findall(rdiv(.*?)/div,html,re.DOTALL)})# re.IGNORECASE: 忽略大小写textPython python PYTHONprint(fIGNORECASE:{re.findall(rpython,text,re.IGNORECASE)})# re.VERBOSE: 允许注释patternr \b # 单词边界 \d{4} # 四位年份 [-/] # 分隔符 \d{1,2} # 月 [-/] # 分隔符 \d{1,2} # 日 \b # 单词边界 date_text日期: 2024-01-15 和 2023/12/25print(fVERBOSE:{re.findall(pattern,date_text,re.VERBOSE)})# 组合标志flagsre.IGNORECASE|re.MULTILINE textHello\nhello\nWORLDprint(f组合标志:{re.findall(r^hello,text,flags)})# # 3. 分组# print(\n*50)print( 分组)print(*50)# 基本分组text张三: 25岁, 北京; 李四: 30岁, 上海patternr(\w):\s*(\d)岁matchesre.findall(pattern,text)print(ffindall 分组:{matches})# 命名分组patternr(?Pname\w):\s*(?Page\d)岁forminre.finditer(pattern,text):print(f{m.group(name)},{m.group(age)}岁)# 非捕获分组 (?:...)textabc123def456print(f捕获:{re.findall(r(\d),text)})print(f非捕获:{re.findall(r(?:\d),text)})# 分组嵌套text2024-01-15mre.match(r(\d{4})-(\d{2})-(\d{2}),text)ifm:print(f完整匹配:{m.group(0)})print(f年:{m.group(1)}, 月:{m.group(2)}, 日:{m.group(3)})print(fgroups:{m.groups()})# # 4. 替换# print(\n*50)print( 替换)print(*50)textHello World Python Programming# sub: 替换所有匹配resultre.sub(r\s, ,text)print(fsub 多空格→单空格: {result})# subn: 返回替换次数result,countre.subn(r\s, ,text)print(fsubn: {result}, 替换{count}次)# 使用函数替换defreplacer(match):wordmatch.group()returnword.upper()iflen(word)3elseword textthe quick brown fox jumps over the lazy dogresultre.sub(r\b\w\b,replacer,text)print(f函数替换: {result})# 反向引用texthello hello world world python pythonresultre.sub(r(\w) \1,r\1,text)print(f去重: {result})# # 5. 分割# print(\n*50)print( 分割)print(*50)textone, two; three|four\tfiveresultre.split(r[,;|\t],text)print(fsplit:{result})# 保留分隔符resultre.split(r([,;|\t]),text)print(fsplit 保留分隔符:{result})# 限制分割次数texta:b:c:d:eresultre.split(r:,text,maxsplit2)print(fmaxsplit2:{result})# # 6. 常用正则模式# print(\n*50)print( 常用正则模式)print(*50)patterns{邮箱:r[\w.-][\w-]\.[\w.-],手机号:r1[3-9]\d{9},IP 地址:r\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3},URL:rhttps?://[\w\-._~:/?#\[\]!$()*,;%],日期:r\d{4}[-/]\d{1,2}[-/]\d{1,2},中文名:r[\u4e00-\u9fa5]{2,4},身份证:r\d{17}[\dXx],}test_texts{邮箱:联系我: testexample.com 或 adminmail.cn,手机号:电话: 13800138000 和 19912345678,IP 地址:服务器: 192.168.1.100 和 10.0.0.1,URL:访问 https://www.example.com/path?qtest,日期:日期: 2024-01-15 和 2023/12/25,中文名:姓名: 张三和李四,身份证:ID: 110101199001011234,}forname,patterninpatterns.items():texttest_texts[name]matchesre.findall(pattern,text)print(f{name}:{matches})# # 7. 实战文本清洗器# print(\n*50)print( 实战文本清洗器)print(*50)dirty_text html body h1Python 教程/h1 p 这是第一段。 有很多 多余的 空格。 /p p 联系邮箱: testexample.com /p p 电话: 13800138000 /p !-- 这是注释 -- scriptalert(xss)/script /body /html classTextCleaner:def__init__(self,text):self.texttextdefremove_html_tags(self):self.textre.sub(r[^],,self.text)returnselfdefremove_html_comments(self):self.textre.sub(r!--.*?--,,self.text,flagsre.DOTALL)returnselfdefnormalize_whitespace(self):self.textre.sub(r[ \t], ,self.text)self.textre.sub(r\n\s*\n,\n,self.text)returnselfdefremove_script_content(self):self.textre.sub(rscript.*?.*?/script,,self.text,flagsre.DOTALL|re.IGNORECASE)returnselfdefextract_emails(self):returnre.findall(r[\w.-][\w-]\.[\w.-],self.text)defextract_phones(self):returnre.findall(r1[3-9]\d{9},self.text)defclean(self):return(self.remove_html_comments().remove_script_content().remove_html_tags().normalize_whitespace().text.strip())cleanerTextCleaner(dirty_text)clean_textcleaner.clean()print(f清洗结果:\n{clean_text})print(f\n提取邮箱:{cleaner.extract_emails()})print(f提取手机:{cleaner.extract_phones()})print(\n[第17章] 全部示例运行完毕)实验日志以下是运行上述代码后的实际输出 基本匹配 search: Python 3.12 match: Python match 数字: None fullmatch: 12345 findall Python: [Python, Python] findall 数字: [3, 12, 2023, 10, 2, 7] finditer: 3.12 at (7, 11) finditer: 2.7 at (35, 38) 匹配模式 MULTILINE ^\w: [Hello, World, Python] MULTILINE \w$: [Hello, World, Python] DOTALL: [\n Hello\n] IGNORECASE: [Python, python, PYTHON] VERBOSE: [2024-01-15, 2023/12/25] 组合标志: [Hello, hello] 分组 findall 分组: [(张三, 25), (李四, 30)] 张三, 25岁 李四, 30岁 捕获: [123, 456] 非捕获: [123, 456] 完整匹配: 2024-01-15 年: 2024, 月: 01, 日: 15 groups: (2024, 01, 15) 替换 sub 多空格→单空格: Hello World Python Programming subn: Hello World Python Programming, 替换 3 次 函数替换: the QUICK BROWN fox JUMPS OVER the LAZY dog 去重: hello world python 分割 split: [one, two, three, four, five] split 保留分隔符: [one, ,, two, ;, three, |, four, \t, five] maxsplit2: [a, b, c:d:e] 常用正则模式 邮箱: [testexample.com, adminmail.cn] 手机号: [13800138000, 19912345678] IP 地址: [192.168.1.100, 10.0.0.1] URL: [https://www.example.com/path?qtest] 日期: [2024-01-15, 2023/12/25] 中文名: [姓名, 张三和李] 身份证: [110101199001011234] 实战文本清洗器 清洗结果: Python 教程 这是第一段。 有很多 多余的 空格。 联系邮箱: testexample.com 电话: 13800138000 提取邮箱: [testexample.com] 提取手机: [13800138000] [第17章] 全部示例运行完毕