python正则表达式——经常使用函数

re.compile()

python re模块提供了一个正则表达式引擎接口,能够将REString编译成对象,并用编译好的对象来匹配。若是一个正则表达式常常用来作匹配,那么能够编译,这样速度更快。python

  • 基本用法以下:
>>> 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也有一些类方法,这里暂时省略,之后补充。app

>>> p = re.compile("abc")
>>> mo = p.match("aaaaabcdrfg")
>>> p = re.compile("abc")
>>> mo1 = p.match("aaaaabcdrfg")
>>> mo2 = p.match("abcdrfg")
>>> print(mo1) #RE没有出如今字符串的开头,所以为None
None
>>> 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匹配的全部子串,并把他们做为一个列表返回。code

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支持正则表达式,使用更加灵活ci

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)

返回一个两个元素的元组,第一个元素表示替换后的结果,第二个元素表示替换的次数。string

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']
相关文章
相关标签/搜索