欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 健康 > 美食 > 【Python】正则表达式

【Python】正则表达式

2024/10/26 0:24:24 来源:https://blog.csdn.net/weixin_57336987/article/details/142032266  浏览:    关键词:【Python】正则表达式

正则表达式

​ 正则表达式,全称是 Regular Expression, 正则表达式, 即: 正确的, 符合特定规则的式子.用来校验和匹配数据,正则不独属于任意的一门语言, Java, Python…都支持, 且: 正则规则都是一样的, 不同的是 写法不一样.

python中正则使用步骤:
# 1.导包import re
# 2. 正则校验.re.match()re.search()re.compile().sub()
# 3. 获取匹配结果.result = re.group()

正则规则如下:

       	.           代表: 任意的1个字符\.          取消.的特殊含义, 就是一个普通的. 校验邮箱的时候用, 例如: zhangsan@163.coma           代表: 就是1个普通的字符a[abc]       代表: a,b,c其中的任意1个字符[^abc]      代表: 除了a,b,c外, 任意的1个字符\d          代表: 所有的数字, 等价于 [0-9]\D          代表: 所有的非数字, 等价于 [^0-9]\s          代表: 空白字符, \n, 空格, \t等...\S          代表: 非空白字符, 即: 上述取反.\w          代表: 非特殊字符, 即: 字母, 数字, _ 下划线, 汉字\W          代表: 特殊字符, 即: 上述取反.^           代表: 开头      '^[^abc].*'$           代表: 结尾?           数量词, 至少0次,至多1次+           数量词, 至少1次, 至多n次*           数量词, 代表前边的内容, 至少出现 0次, 至多出现 n次{n}         恰好n次, 多一次少一次都不行.{n,}        至少n次, 至多无所谓{n,m}       至少n次, 至多m次, 包括n和m|           或者的意思.()			分组\num		\分组编号, 表示引入某组的内容.(?P<分组名>)       给分组起名字(?P=分组名)        使用指定分组的内容

具体代码示例:

正则替换
import reif __name__ == '__main__':# 案例1: 把下述的符合正则规则的内容, 用*来替换.# 1. 定义 旧字符串.old_str = '你可以这样: 桀1桀2桀, 哈3哈, 呵A呵, 嘿嘿, 嘻嘻, 略略略, 嘤嘤嘤...'# 2. 定义 正则规则(字符串形式)reg_exp = '桀|哈|呵|嘿|嘻'# 3. 把符合正则规则的内容, 用*来替换.# 分解版写法.# 3.1 获取正则对象.# re_obj = re.compile(reg_exp)# 3.2 具体的替换过程.# result = re_obj.sub('*', old_str)# 合并版写法,         正则规则       新内容     旧内容# result = re.compile(reg_exp).sub('*', old_str)# 上述格式的语法糖, 正则规则   新内容     旧内容result = re.sub(reg_exp, '*', old_str)# 4 打印结果print(result)print('-' * 21)# 案例2: 回顾字符串的replace()函数.s1 = '抽烟只抽煊赫门, 一生只爱一个人. 其他烟: 中华, 煊赫门, 天叶, 煊赫门...'# result = s1.replace('煊赫门', '*')     # 不写次数, 默认替换所有.# result = s1.replace('煊赫门', '*', 1)  # 只替换1次(个)result = s1.replace('煊赫门|中华|天叶', '*')print(f'result:  {result}')
校验单个字符
if __name__ == '__main__':# 演示: .           代表: 任意的1个字符, \n除外result = re.match('csdn.', 'csdna')     # csdnaresult = re.match('csdn.', 'csdn\t')    # csdn\tresult = re.match('csdn.', 'csdn\n')    # 未匹配# 演示: \.          代表: 1个普通的.  即: 取消.的特殊含义# 细节: 为了防止打印异常信息, 你可以写成: r'csdn\.'  或者 'csdn\\.'result = re.match('csdn\\.', 'csdna')        # 未匹配result = re.match('csdn\\.', 'csdn.')        # csdn.result = re.match('csdn\\.', 'csdn.abc')     # csdn.# 演示: a           代表: 1个字符aresult = re.match('a', 'abc')            # aresult = re.match('a', 'xyz')            # 未匹配# 演示: [abc]       代表: a, b, c中任意的1个字符, 即: 要么a, 要么b, 要么cresult = re.match('csdn[abc]', 'csdnabc')    # csdnaresult = re.match('csdn[abc]', 'csdnbc')     # csdnbresult = re.match('csdn[abc]', 'csdnd')      # 未匹配# 演示: [^abc]      代表: 除了a,b,c外, 任意的1个字符result = re.match('csdn[^abc]', 'csdnabc')  # 未匹配result = re.match('csdn[^abc]', 'csdnbc')   # 未匹配result = re.match('csdn[^abc]', 'csdnd')    # csdnd# 演示: \d          代表: 任意的1个整数, 等价于 [0-9]result = re.match('abcdefg[0-9]', 'abcdefg1')     # abcdefg1result = re.match('abcdefg[0-9]', 'abcdefg3a')    # abcdefg3result = re.match(r'abcdefg\d', 'abcdefg3a')      # abcdefg3result = re.match(r'abcdefg\d', 'abcdefga')      # 未匹配# 演示: \D          代表: 任意的1个非整数, 等价于 [^0-9]result = re.match(r'abcdefg\D', 'abcdefga')   # abcdefgaresult = re.match(r'abcdefg\D', 'abcdefg3a')  # 未匹配# 演示: \w          代表: 非特殊字符, 即: 大小写英文字符, 数字, _, 汉字result = re.match(r'abcdefg\w', 'abcdefga')  # abcdefgaresult = re.match(r'abcdefg\w', 'abcdefgB')  # abcdefgBresult = re.match(r'abcdefg\w', 'abcdefg1')  # abcdefg1result = re.match(r'abcdefg\w', 'abcdefg_')  # abcdefg_result = re.match(r'abcdefg\w', 'abcdefg!')  # 未匹配# 演示: \W          代表: 特殊字符, 即: \w 取反.result = re.match(r'abcdefg\W', 'abcdefg!')  # abcdefg!result = re.match(r'abcdefg\W', 'abcdefg_')  # 未匹配# 演示: \s          代表: 空白字符, 例如: 空格, \t...result = re.match(r'abcdefg\s', 'abcdefg')    # 未匹配result = re.match(r'abcdefg\s', 'abcdefg ')   # abcdefgresult = re.match(r'abcdefg\s', 'abcdefg\t')  # abcdefgresult = re.match(r'abcdefg\s', 'abcdefg\n')  # abcdefg\nresult = re.match(r'abcdefg\s', 'abcdefga')   # 未匹配# 演示: \S          代表: 非空白字符, 即: \s取反.# 自己测试.# 打印校验到的数据.if result:print(f'匹配到: {result.group()}')else:print('未匹配!')
校验多个字符
import re# main中测试
if __name__ == '__main__':# 演示: ?           代表: 前边的内容, 出现0次 或者 1次result = re.match('csdn.?', 'csdn')result = re.match('csdn.?', 'csdn ')result = re.match('csdn.?', 'csdnabcABC')result = re.match('csdn.?', 'csdn\nABC')    # csdn# 演示: *           代表: 前边的内容, 至少出现0次, 至多出现n次(无数次)result = re.match('csdn[abc]*', 'csdn\nABC')  # csdnresult = re.match('csdn[abc]*', 'csdnabcABC') # csdnabcresult = re.match('csdn[abc]*', 'csdn ')      # csdnresult = re.match('csdn[abc]*', 'csdn')       # csdn# 演示: +           代表: 前边的内容, 出现1次 或者 多次.result = re.match('csdn[abc]+', 'csdn')   # 未匹配result = re.match('csdn[abc]+', 'csdn ')  # 未匹配result = re.match('csdn[abc]+', 'csdn\nABC')  # 未匹配result = re.match('csdn[abc]+', 'csdnabcABC')  # csdnabc# 演示: a{n}        代表: a恰好出现n次, 多一次少一次都不行.result = re.match('csdn[abc]{2}', 'csdnabcABC')  # csdnabresult = re.match('csdn[abc]{2}', 'csdnacb')     # csdnacresult = re.match('csdn[abc]{2}', 'csdna')       # 未匹配# 演示: a{n,}       代表: a至少出现n次, 至多无所谓.result = re.match('csdn[abc]{2,}', 'csdna')         # 未匹配result = re.match('csdn[abc]{2,}', 'csdnacb')       # csdnacbresult = re.match('csdn[abc]{2,}', 'csdnabcABC')    # csdnabc# 演示: a{n,m}      代表: a至少出现n次, 至多出现m次, 包括n 和 mresult = re.match('csdn[abc]{2,3}', 'csdnabcde')     # csdnabcresult = re.match('csdn[abc]{2,3}', 'csdna')         # 未匹配# 打印结果.print(f'匹配到: {result.group()}' if result else '未匹配!')
校验开头和结尾
import reif __name__ == '__main__':# 演示: ^       代表: 正则表达式的 开头# 需求: 校验字符串必须以 it 开头.result = re.match(r'it\d', 'it123')      # it1result = re.match(r'it\d', '1it123')     # 未匹配!result = re.search(r'it\d', 'it123')   # it1result = re.search(r'it\d', '1it123')  # it1# ^代表开头, 即: 如下的代码其实是 全词匹配, 必须从字符串的第1个字符开始校验.result = re.search(r'^it\d', '1it123')  # 未匹配!# 演示: $       代表: 正则表达式的 结尾# 需求: 校验字符串必须以 数字 结尾.result = re.match(r'it\d', 'it123a')      # it1result = re.match(r'it\d$', 'it123a')     # 未匹配!# 扩展: 校验手机号.# 规则: 1. 必须以1开头.   2.第2位数字可以是3 ~ 9.  3.必须是纯数字.  4.长度必须是11位.result = re.match(r'^1[3-9]\d{9}$', '13112345678a')result = re.match(r'^1[3-9]\d{9}$', '13112345678')# 打印匹配到的结果.print(result.group()  if result else '未匹配!')
校验分组
import reif __name__ == '__main__':# 需求1: 在列表中, 打印用户喜欢吃 和 不喜欢吃的水果.# 1. 定义水果列表.fruits = ['apple', 'banana', 'orange', 'pear']# 2. 遍历, 获取每种水果.for fruit in fruits:# 3. 假设用户喜欢吃 香蕉, 梨, 判断即可.result = re.match('banana|pear', fruit)# 4. 打印结果.if result:print(f'喜欢吃: {fruit}')else:print(f'不喜欢吃: {fruit}')
校验邮箱
import reif __name__ == '__main__':# 需求: 匹配出 163, 126, qq等邮箱.# 邮箱规则: 前边是4 ~ 20位的字母, 数字, 下划线 + @标记符 + 域名# 1. 定义邮箱字符串.email_str = 'zhangsan@163com'email_str = 'zhangsan@1634.com'email_str = 'zh@qq.com'email_str = 'zhangsan@163.com'# 2. 定义 校验邮箱的 正则表达式.pattern = r'^[a-zA-Z0-9_]{4,20}@(163|126|qq)\.com$'# 3. 校验邮箱.result = re.match(pattern, email_str)# 4. 打印结果.if result:print(f'匹配到: {result.group()}')     # zhangsan@163.com, 等价于 result.group(0), 即: 获取所有匹配到的数据print(f'匹配到: {result.group(0)}')    # zhangsan@163.com, 效果同上.print(f'匹配到: {result.group(1)}')    # 163else:print('未匹配!')
提取指定的分组的数据
import reif __name__ == '__main__':# 需求: 匹配 qq:qq号 这样的数据, 提取出 qq文字 和 qq号码.# 1. 定义字符串.s1 = "qq:1234567"# 2. 匹配数据.result = re.match(r'(qq):(\d{6,11})', s1)# 3. 打印匹配到的数据.if result:print(f'匹配到: {result.group()}')     # qq:1234567print(f'匹配到: {result.group(0)}')    # qq:1234567print(f'匹配到: {result.group(1)}')    # qqprint(f'匹配到: {result.group(2)}')    # 1234567else:print('未匹配!')
引用指定的内容
import reif __name__ == '__main__':# 需求1: 正则校验 html标签, 简单版.# 1. 定义html标签字符串.html_str1 = '<html>csdnpy</html>'# 2. 正则校验.# 假设: 标签规则: 2到4位字母result = re.match('<[a-zA-Z]{2,4}>.*</[a-zA-Z]{2,4}>', html_str1)# 上述格式优化版, 加入: 分组思想.result = re.match(r'<([a-zA-Z]{2,4})>.*</\1>', html_str1)# 3. 打印匹配结果.if result:print(f'匹配到: {result.group()}')else:print('未匹配!')print('-' * 21)# 需求2: 正则校验 html标签, 升级版.# 假设: 外部标签规则 2到4位字母,  内部标签规则: h + 1到6的数字# 1. 定义html标签字符串.html_str2 = '<html><h1>csdnpy</h1></html>'# 2. 正则校验result = re.match(r'<[a-zA-Z]{2,4}><h[1-6]>.*</h[1-6]></[a-zA-Z]{2,4}>', html_str2)# 加入分组, 优化上述的代码.result = re.match(r'<([a-zA-Z]{2,4})><(h[1-6])>.*</\2></\1>', html_str2)# 扩展: 给分组设置组名.result = re.match(r'<(?P<A>[a-zA-Z]{2,4})><(?P<B>h[1-6])>.*</(?P=B)></(?P=A)>', html_str2)# 3. 打印匹配结果.if result:print(f'匹配到: {result.group()}')else:print('未匹配!')

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com