正则表达式
模块为re,需要单独引入。其中常用的函数有:(来自骆峰的博客)
函数 | 功能 |
---|---|
compile(pattern, flags=0) | 编译正则表达式返回正则表达式对象 |
search(pattern, string, flags=0) | 搜索字符串中第一次出现正则表达式的模式 成功返回匹配对象 否则返回None |
sub(pattern, repl, string, count=0, flags=0) | 用指定的字符串替换原字符串中与正则表达式匹配的模式 可以用count指定替换的次数 |
split(pattern, string, maxsplit=0, flags=0) | 用正则表达式指定的模式分隔符拆分字符串 返回列表 |
findall(pattern, string, flags=0) | 查找字符串所有与正则表达式匹配的模式 返回字符串的列表 |
re.I | 不区分大小写 |
re.VERBOSE | 允许在正则表达式中分行并加注释 |
其中要注意,各个函数中的pattern参数既可以是正则表达式字符串,也可以是re.compile()函数的返回值,二者都可以充当匹配模式pattern。即:
pattern = re.compile(r'(?<=\D)1[34578]\d{9}(?=\D)') # 其中[]为匹配括号内任意“一位”字符
"""则以下两种写法是完全等价的"""
mylist = re.findall(pattern, sentence)
mylist2 = re.findall(r'(?<=\D)1[34578]\d{9}(?=\D)', sentence)
那么为什么还要使用compile函数多此一举呢?因为compile函数的返回对象有正则表达式字符串所没有的、很方便的、以上函数的“同名”方法,如:
pattern = re.compile(r'(?<=\D)1[34578]\d{9}(?=\D)')
"""则以下三种写法是完全等价"""
mylist = re.findall(pattern, sentence) # findall为re模块里的函数
mylist2 = re.findall(r'(?<=\D)1[34578]\d{9}(?=\D)', sentence)
mylist3 = pattern.findall(sentence) # 此findall为pattern对象中的方法
# 与同名函数findall对应,但是用上不完全相同
这种运用方式对于以上列的各种常用函数来说都是适用的,可以省略对模式的输入。当一种匹配模式要多次使用时,compile的优势便显示出来。
类中其他的“特殊方法”
除了特殊属性__slots__以及特殊方法__init__()以外,类定义中还有其他的特殊方法和属性可以使用(都以双下划线开头双下划线结尾)。
__str__()和__repr__()
该方法返回