python compile正则_Python 正则表达式:compile

本文以匹配×××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 -*-

import re;

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 -*-

import re;

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 -*-

import re;

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 -*-

import re;

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值