re.compile()
python re模块提供了一个正则表达式引擎接口,可以将REString编译成对象,并用编译好的对象来匹配。如果一个正则表达式经常用来做匹配,那么可以编译,这样速度更快。
- 基本用法如下:
>>> import re>>> p = re.compile("c[a-g]t")>>> print(p)<_sre.SRE_Pattern object at 0x11e6420>>>> p.findall("cat cbtt")['cat', 'cbt']
- 可以接受可选标志参数,实现不同的特殊功能和语法变更。
re.I 不区分大小写 ......
>>> p = re.compile("c[a-g]t", re.I)>>> p.findall("cat cBTt")['cat', 'cBT']
- 反斜杠
re.match()
若RE在字符串开始的位置匹配,则返回一个'matchObject'实例(对象);否则返回None。 通常用法是将match的返回值赋给一个变量,然后判断这个变量是否在None。 当然,返回的matchObject也有一些类方法,这里暂时省略,以后补充。
>>> p = re.compile("abc")>>> mo = p.match("aaaaabcdrfg")>>> p = re.compile("abc")>>> mo1 = p.match("aaaaabcdrfg")>>> mo2 = p.match("abcdrfg")>>> print(mo1) #RE没有出现在字符串的开头,因此为NoneNone>>> print(mo2)<_sre.SRE_Match object at 0x12425e0>>>> mo3 = p.search("aaaaabcdrfg")>>> mo4 = p.search("abcdrfg")>>> print(mo3)<_sre.SRE_Match object at 0x1309b28>>>> print(mo4)<_sre.SRE_Match object at 0x1309b90>
re.search()
扫描字符串,找到RE匹配的位置,成功则返回一个'matchObject'实例(对象);否则返回None。
re.findall()
找到RE匹配的所有子串,并把他们作为一个列表返回。
re.finditer()
找到RE匹配的所有子串,并把他们作为一个迭代器返回。
re.sub()
sub(pattern, repl, string, count=0, flags=0) Return the string obtained by replacing the leftmost non-overlapping occurrences of the pattern in string by the replacement repl. repl can be either a string or a callable; if a string, backslash escapes in it are processed. If it is a callable, it's passed the match object and must return a replacement string to be used.
>>> re.sub(r"a", "b", "haha") # count=0或者省略表示全部替换'hbhb'>>> re.sub(r"a", "b", "haha", 0)'hbhb'>>> re.sub(r"a", "b", "haha", 1)# count=1表示全部替换1次'hbha'
这里与字符串函数replace区别就是,re.sub()的pattern支持正则表达式,使用更加灵活
re.subn()
subn(pattern, repl, string, count=0, flags=0) Return a 2-tuple containing (new_string, number). new_string is the string obtained by replacing the leftmost non-overlapping occurrences of the pattern in the source string by the replacement repl. number is the number of substitutions that were made. repl can be either a string or a callable; if a string, backslash escapes in it are processed. If it is a callable, it's passed the match object and must return a replacement string to be used.
>>> re.subn(r"a", "b", "haha") #参数与sub一样('hbhb', 2)>>> re.subn(r"a", "b", "haha", 1)('hbha', 1)>>> re.subn(r"a", "b", "haha", 2)('hbhb', 2)
返回一个两个元素的元组,第一个元素表示替换后的结果,第二个元素表示替换的次数。
re.split()
split(pattern, string, maxsplit=0, flags=0) Split the source string by the occurrences of the pattern, returning a list containing the resulting substrings. 这个函数与字符串的split区别就是这里的pattern支持正则表达式,使用更加灵活。
>>> re.split(r"[a-f]", "afternoon")['', '', 't', 'rnoon']