python re.compile()方法,获取正则表达式对象
re.compile()方法
python re正则表达式模块中的compile()可以将参数指定的正则表达式编译成正则表达式对象,方便调用,提高开发效率。如源码中的介绍。
语法
compile(pattern, flags=0)
python源码对compile()方法的介绍:
Compile a regular expression pattern, returning a pattern object.
参数
参数 | 描述 |
---|---|
pattern | python字符串类型,指定正则表达式 |
flags | 编译标志位,默认为0,可用来指定正则表达式的匹配模式 |
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:该值允许开发者将正则表达式写成更易于理解的格式。
返回值
正则表达式对象。
re.compile()方法实例代码
>>> import re
>>> string = '笨鸟工具,x1y1z1.com'
>>> c = re.compile('[,]+')
>>> list1 = c.split(string)
>>> list1
['笨鸟工具', 'x1y1z1.com']