python中re.compile()用法详解
学习Python基础语法:https://www.runoob.com/python/python-tutorial.html #生活技巧# #工作学习技巧# #编程学习资源#
编译正则表达式模式,返回一个对象。可以把常用的正则表达式编译成正则表达式对象,方便后续调用及提高效率。
源码解析:
def compile(pattern, flags=0):
"Compile a regular expression pattern, returning a Pattern object."
return _compile(pattern, flags)
python
语法结构:
re.compile(pattern, flags=0)
python
pattern 指定编译时的表达式字符串flags 编译标志位,用来修改正则表达式的匹配方式。支持 re.L|re.M 同时匹配flags 标志位参数:
re.I(re.IGNORECASE) :使匹配对大小写不敏感re.L(re.LOCAL) :做本地化识别(locale-aware)匹配re.M(re.MULTILINE) :多行匹配,影响 ^ 和 $re.S(re.DOTALL) :使 . 匹配包括换行在内的所有字符re.U(re.UNICODE):根据Unicode字符集解析字符。这个标志影响 \w, \W, \b, \B.re.X(re.VERBOSE):该标志通过给予你更灵活的格式以便你将正则表达式写得更易于理解。示例代码1:
import re
s = 'a,b,,,,c d'
a = re.compile('[, ]+')
b = a.split(s)
print(a)
print(b)
c = re.compile('[,]+')
d = c.split(s)
print(d)
python
运行结果:

示例代码2: 【对比示例代码1,不使用re.compile()】
import re
s = 'a,b,,,,c d'
b = re.split('[, ]+', s)
print(b)
d = re.split('[,]+', s)
print(d)
python
运行结果:

示例代码3: 【使用re.I:对大小写不敏感】
import re
s = 'aBdfbksdBjksdbsk'
aa = re.compile('b')
bb = aa.split(s)
print(bb)
s = 'aBdfbksdBjksdbsk'
aa = re.compile('b', re.I)
bb = aa.split(s)
print(bb)
python
运行结果:

示例代码4: 【匹配手机号】
import re
s1 = 'num:12345678900,name:dgw,phone:19876543210,age:25'
s2 = 'num:12345678900,name:dgw,phone:119876543210,age:25'
aa = re.compile(r'(?<=\D)1[3456789]\d{9}', re.S)
bb = aa.findall(s1)
print(bb)
cc = re.compile(r'(?<=\D)1[3456789]\d{9}', re.S)
dd = cc.findall(s2)
print(dd)
ee = re.compile(r'1[3456789]\d{9}', re.S)
ff = ee.findall(s2)
print(ff)
gg = re.compile(r'(?<=\d)1[3456789]\d{9}', re.S)
hh = gg.findall(s2)
print(hh)
python
运行结果:

网址:python中re.compile()用法详解 https://www.yuejiaxmz.com/news/view/1438151
相关内容
python 中re模块的re.compile()方法Python中正则模块re.compile、re.match及re.search函数用法
re.compile(pattern,flags=0)中flags的用法
正则表达式re.compile()的使用
用python 玩微信
Python中的不等于运算符详解
Python学习(一)
PYTHON SERIAL COMMUNICATION
Python中sort和sorted函数用法解析
使用Python和百度地图API实现路径规划算法的详细步骤

