Python 正则表达式:compile,match
本文以匹配×××ID为例,介绍re模块的compile与match的用法
复杂匹配 = re.compile(正则表达式): 将正则表达式实例化
+
re.match(要匹配的字符串): 从字符串开 头/尾 开始匹配
简单匹配 = re.match(正则表达式,要匹配的字符串): 从字符串开 头/尾 开始匹配
懒癌,配上模块函数解释好消化
re.match(pattern,string,flags)第一个参数是正则表达式,如果匹配成功,则返回一个Match,否则返回一个None;第二个参数表示要匹配的字符串;第三个参数是标致位,用于控制正则表达式的匹配方式,如:是否区分大小写,多行匹配等等。需要特别注意的是,这个方法并不是完全匹配。它仅仅决定在字符串开始的位置是否匹配。所以当pattern结束时若还有剩余字符,仍然视为成功。想要完全匹配,可以在表达式末尾加上边界匹配符'$'例如:match(‘p’,’python’)返回值为真;match(‘p’,’www.python.org’)返回值为假---------------------作者:24k千足金闪闪大宝贝猫的小熊来源:CSDN原文:https://blog.csdn.net/piglite/article/details/81121323版权声明:本文为博主原创文章,转载请附上博文链接!
方法一:
re.compile(正则表达式).match(要比配的字符串)
#!/usr/bin/python#!-*-coding:utf-8-*-importre;id_num='440211199606030022'id_pat='(^\d{14}(\d|x)$|(^\d{17}(\d|x)$))'id_str=re.compile(id_pat).match(id_num)print("Match:"+str(id_str.group()))
运行结果:
Match:440211199606030022
方法二:
对象名1 =re.compile(正则表达式)
对象名2 = 对象名1.match(要比配的字符串)
#!/usr/bin/python#!-*-coding:utf-8-*-importre;id_num='440211199606030022'id_pat='(^\d{14}(\d|x)$|(^\d{17}(\d|x)$))'id_instantiation=re.compile(id_pat)id_str=id_instantiation.match(id_num)print("Match:"+str(id_str.group()))
运行结果:
Match:440211199606030022
方法三:
对象名1 =re.compile(正则表达式)
对象名2 = re.match(对象名1, 要比配的字符串)
#!/usr/bin/python#!-*-coding:utf-8-*-importre;id_num='440211199606030022'id_pat='(^\d{14}(\d|x)$|(^\d{17}(\d|x)$))'id_instantiation=re.compile(id_pat)id_str=re.match(id_instantiation,id_num)print("Match:"+str(id_str.group()))
运行结果:
Match:440211199606030022
方法四:
对象名1 = 正则表达式
对象名2 = re.compile(对象名1,要比配的字符串)
#!/usr/bin/python#!-*-coding:utf-8-*-importre;id_num='440211199606030022'id_pat='(^\d{14}(\d|x)$|(^\d{17}(\d|x)$))'id_str=re.match(id_pat,id_num)print("Match:"+str(id_str.group()))
运行结果:
Match:440211199606030022
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。