Python正则表达式

来源:互联网 发布:长江期货软件下载 编辑:程序博客网 时间:2024/06/06 18:44

正则表达式的大致匹配过程是:依次拿出表达式和文本中的字符比较,如果每一个字符都能匹配,则匹配成功;一旦有匹配不成功的字符则匹配失败。

  • 贪婪模式和非贪婪模式。

主要是*和?的区别。前者匹配尽可能多,后者匹配尽可能少

>>> import re>>> a = "abbbb">>> pattern = re.compile('ab*')>>> match = pattern.match(a)>>> print match.group()abbbb>>> pattern = re.compile('ab?')>>> match = pattern.match(a)>>> print match.group()ab>>> pattern = re.compile('ab*?')>>> match = pattern.match(a)>>> print match.group()a
  • 常用方法

(1) Pattern

Pattern对象是一个编译好的正则表达式,通过Pattern提供的一系列方法可以对文本进行匹配查找。

Pattern不能直接实例化,必须使用re.compile()进行构造。随后通过re.match(str)或者re.search(str)

match(string[, pos[, endpos]]) | re.match(pattern, string[, flags]): 

这个方法将从string的pos下标处起尝试匹配pattern;如果pattern结束时仍可匹配,则返回一个Match对象;

如果匹配过程中pattern无法匹配,或者匹配未结束就已到达endpos,则返回None。 

pos和endpos的默认值分别为0和len(string);re.match()无法指定这两个参数,参数flags用于编译pattern时指定匹配模式。 

注意:这个方法并不是完全匹配。当pattern结束时若string还有剩余字符,仍然视为成功。想要完全匹配,可以在表达式末尾加上边界匹配符'$'。 

search(string[, pos[, endpos]]) | re.search(pattern, string[, flags]): 

这个方法用于查找字符串中可以匹配成功的子串。从string的pos下标处起尝试匹配pattern,如果pattern结束时仍可匹配,则返回一个Match对象;

若无法匹配,则将pos加1后重新尝试匹配;直到pos=endpos时仍无法匹配则返回None。 

pos和endpos的默认值分别为0和len(string));re.search()无法指定这两个参数,参数flags用于编译pattern时指定匹配模式。 

split(string[, maxsplit]) | re.split(pattern, string[, maxsplit]): 

按照能够匹配的子串将string分割后返回列表。maxsplit用于指定最大分割次数,不指定将全部分割。 

>>> p = re.compile(r'\d+')>>> print p.split('one1two2three3four4')['one', 'two', 'three', 'four', '']

findall(string[, pos[, endpos]]) | re.findall(pattern, string[, flags]): 

搜索string,以列表形式返回全部能匹配的子串。

>>> print p.findall("'one1two2three3four4'")['1', '2', '3', '4']

finditer(string[, pos[, endpos]]) | re.finditer(pattern, string[, flags]): 

搜索string,返回一个顺序访问每一个匹配结果(Match对象)的迭代器。 

>>> for m in p.finditer('one1two2three3four4'):    print m.group(),1 2 3 4

finditer函数和findall函数的区别是,findall返回所有匹配的字符串,并存为一个列表,而finditer则并不直接返回这些字符串,而是返回一个迭代器。

关于迭代器,解释起来有点复杂,还是看看例子把:

>>> for m in p.finditer('one1two2three3four4'):    print m.group(),m.span() #打印每次得到的字符和起始结束位置  1 (3, 4)2 (7, 8)3 (13, 14)4 (18, 19)

简单的说吧,就是finditer返回了一个可调用的对象,使用 for i in finditer()的形式,可以一个一个的得到匹配返回的 Match对象。对每次返回的对象进行比较复杂的操作时比较有用。

sub(repl, string[, count]) | re.sub(pattern, repl, string[, count]): 

使用repl替换string中每一个匹配的子串后返回替换后的字符串。 

当repl是一个字符串时,可以使用\id或\g<id>、\g<name>引用分组,但不能使用编号0。 

当repl是一个方法时,这个方法应当只接受一个参数(Match对象),并返回一个字符串用于替换(返回的字符串中不能再引用分组)。

count用于指定最多替换次数,不指定时全部替换。 

subn(repl, string[, count]) |re.sub(pattern, repl, string[, count]): 

返回 (sub(repl, string[, count]), 替换次数)。 

>>> p = re.compile(r'(\w+) (\w+)')<span style="white-space:pre">#匹配每个单词>>> s = 'i say, hello world!'>>> print p.subn(r'\2 \1', s)<span style="white-space:pre">#\number表示引用number分组分配到的字符串('say i, world hello!', 2)>>> def func(m):    return m.group(1).title() + ' ' + m.group(2).title()>>> print p.subn(func, s)('I Say, Hello World!', 2)

  • re.compile(Pattern[, flag])

这个方法是Pattern类的工厂方法,用于将字符串形式的正则表达式编译为Pattern对象。

 第二个参数flag是匹配模式,取值可以使用按位或运算符'|'表示同时生效,比如re.I | re.M。

可选值有:

re.I(re.IGNORECASE): 忽略大小写(括号内是完整写法,下同)

M(MULTILINE): 多行模式,改变'^'和'$'的行为

S(DOTALL): 点任意匹配模式,改变'.'的行为

L(LOCALE): 使预定字符类 \w \W \b \B \s \S 取决于当前区域设定

U(UNICODE): 使预定字符类 \w \W \b \B \s \S \d \D 取决于unicode定义的字符属性

X(VERBOSE): 详细模式。这个模式下正则表达式可以是多行,忽略空白字符,并可以加入注释。以下两个正则表达式是等价的:

a = re.compile(r"""\d +  # the integral part                   \.    # the decimal point                   \d *  # some fractional digits""", re.X)b = re.compile(r"\d+\.\d*")

re提供了众多模块方法用于完成正则表达式的功能。这些方法可以使用Pattern实例的相应方法替代,唯一的好处是少写一行re.compile()代码,但同时也无法复用编译后的Pattern对象。这些方法将在Pattern类的实例方法部分一起介绍。如上面这个例子可以简写为:

m = re.match(r'hello', 'hello world!')print m.group()

re模块还提供了一个方法escape(string),用于将string中的正则表达式元字符如*/+/?等之前加上转义符再返回,在需要大量匹配元字符时有那么一点用。

>>> m = re.match(r'(\w+) (\w+)(?P<sign>.*)', 'hello world!')>>> print m.stringhello world!>>> print m.re<_sre.SRE_Pattern object at 0x0000000002E7EE00>>>> print m.pos #正则表达式开始搜索的索引0>>> print m.endpos #正则表达式结束搜索的索引12>>> print m.lastindex   #最后一个被捕获的分组在文本中的索引。如果没有被捕获的分组,将为None。3>>> print m.group(1,2) #获得一个或多个分组截获的字符串;指定多个参数时将以元组形式返回。默认编号0代表整个匹配的子串;没有截获返回None('hello', 'world')>>> print m.groups() #以元组形式返回全部分组截获的字符串。相当于调用group(1,2,…last)。没有截获字符串的组以括号内值替代,默认None。</span>('hello', 'world', '!')>>> print m.groupdict() #返回以有别名的组的别名为键、以该组截获的子串为值的字典,没有别名的组不包含在内。{'sign': '!'}>>> print m.start(2) #返回指定的组截获的子串在string中的起始索引(子串第一个字符的索引)。group默认值为0。6>>> print m.end(2) #返回指定的组截获的子串在string中的结束索引(子串最后一个字符的索引+1)。group默认值为0。</span>11>>> print m.span(2)#返回(start(group), end(group))。(6, 11)>>> print m.expand(r'\2 \1\3')#将匹配到的分组代入template中然后返回。template中可以使用\id或\g<id>、\g<name>引用分组,但不能使用编号0。\id与\g<id>是等价的;但\10将被认为是第10个分组,如果你想表达\1之后是字符'0',只能使用\g<1>0。world hello!>>> 

0 0