【Python3之正则re】

 

 一、正则re

1.正则表达式定义

正则就是用一些具有特殊含义的符号组合到一起(称为正则表达式)来描述字符或者字符串的方法。或者说:正则就是用来描述一类事物的规则。(在Python中)它内嵌在Python中,并通过 re 模块实现。正则表达式模式被编译成一系列的字节码,然后由用 C 编写的匹配引擎执行。

2.常用的正则表达式

pyre

3.贪婪模式与非贪婪模式

正则表达式通常用于在文本中查找匹配的字符串。Python里数量词默认是贪婪的(在少数语言里也可能是默认非贪婪),总是尝试匹配尽可能多的字符;非贪婪的则相反,总是尝试匹配尽可能少的字符。例如:正则表达式"ab*"如果用于查找"abbbc",将找到"abbb"。而如果使用非贪婪的数量词"ab*?",将找到"a"。 

4.反斜杠

与大多数编程语言相同,正则表达式里使用""作为转义字符,这就可能造成反斜杠困扰。假如你需要匹配文本中的字符"",那么使用编程语言表示的正则表达式里将需要4个反斜杠"\\":前两个和后两个分别用于在编程语言里转义成反斜杠,转换成两个反斜杠后再在正则表达式里转义成一个反斜杠。Python里的原生字符串很好地解决了这个问题,这个例子中的正则表达式可以使用r"\"表示。同样,匹配一个数字的"\d"可以写成r"d"。有了原生字符串,你再也不用担心是不是漏写了反斜杠,写出来的表达式也更直观。

5.re模块

Python通过re模块提供对正则表达式的支持。使用re的一般步骤是先将正则表达式的字符串形式编译为Pattern实例,然后使用Pattern实例处理文本并获得匹配结果(一个Match实例),最后使用Match实例获得信息,进行其他的操作。

Match

Match对象是一次匹配的结果,包含了很多关于此次匹配的信息,可以使用Match提供的可读属性或方法来获取这些信息。

属性:

  1. string: 匹配时使用的文本。 
  2. re: 匹配时使用的Pattern对象。 
  3. pos: 文本中正则表达式开始搜索的索引。值与Pattern.match()和Pattern.seach()方法的同名参数相同。 
  4. endpos: 文本中正则表达式结束搜索的索引。值与Pattern.match()和Pattern.seach()方法的同名参数相同。 
  5. lastindex: 最后一个被捕获的分组在文本中的索引。如果没有被捕获的分组,将为None。 
  6. lastgroup: 最后一个被捕获的分组的别名。如果这个分组没有别名或者没有被捕获的分组,将为None。 

方法:

  • group([group1, …]): 

获得一个或多个分组截获的字符串;指定多个参数时将以元组形式返回。group1可以使用编号也可以使用别名;编号0代表整个匹配的子串;不填写参数时,返回group(0);没有截获字符串的组返回None;截获了多次的组返回最后一次截获的子串。 

  • groups([default]):

以元组形式返回全部分组截获的字符串。相当于调用group(1,2,…last)。default表示没有截获字符串的组以这个值替代,默认为None。 

  • groupdict([default]): 

返回以有别名的组的别名为键、以该组截获的子串为值的字典,没有别名的组不包含在内。default含义同上。 

  • start([group]):

返回指定的组截获的子串在string中的起始索引(子串第一个字符的索引)。group默认值为0。 

  • end([group]): 

返回指定的组截获的子串在string中的结束索引(子串最后一个字符的索引+1)。group默认值为0。 

  • span([group]): 

返回(start(group), end(group))。 

  • expand(template):

将匹配到的分组代入template中然后返回。template中可以使用id或g<id>、g<name>引用分组,但不能使用编号0。id与g<id>是等价的;但10将被认为是第10个分组,如果你想表达1之后是字符'0',只能使用g<1>0。

例:

复制代码
import re
m = re.match(r'(w+) (w+)(?P<sign>.*)', 'hello world!')

print("m.string:", m.string)
print("m.re:", m.re)
print("m.pos:", m.pos)
print("m.endpos:", m.endpos)
print("m.lastindex:", m.lastindex)
print("m.lastgroup:", m.lastgroup)

print("m.group(1,2):", m.group(1, 2))
print("m.groups():", m.groups())
print("m.groupdict():", m.groupdict())
print("m.start(2):", m.start(2))
print("m.end(2):", m.end(2))
print("m.span(2):", m.span(2))
print(r"m.expand(r'2 13'):", m.expand(r'2 13'))
复制代码

输出

复制代码
m.string: hello world!
m.re: re.compile('(\w+) (\w+)(?P<sign>.*)')
m.pos: 0
m.endpos: 12
m.lastindex: 3
m.lastgroup: sign
m.group(1,2): ('hello', 'world')
m.groups(): ('hello', 'world', '!')
m.groupdict(): {'sign': '!'}
m.start(2): 6
m.end(2): 11
m.span(2): (6, 11)
m.expand(r'2 13'): world hello!
复制代码

Pattern

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

Pattern不能直接实例化,必须使用re.compile()进行构造。

Pattern提供了几个可读属性用于获取表达式的相关信息:

  1. pattern: 编译时用的表达式字符串。 
  2. flags: 编译时用的匹配模式。数字形式。 
  3. groups: 表达式中分组的数量。 
  4. groupindex: 以表达式中有别名的组的别名为键、以该组对应的编号为值的字典,没有别名的组不包含在内。

例:

复制代码
import re
p = re.compile(r'(w+) (w+)(?P<sign>.*)', re.DOTALL)

print("p.pattern:", p.pattern)
print("p.flags:", p.flags)
print("p.groups:", p.groups)
print("p.groupindex:", p.groupindex)
复制代码

输出

p.pattern: (w+) (w+)(?P<sign>.*)
p.flags: 48
p.groups: 3
p.groupindex: {'sign': 3}

实例方法[ | re模块方法]:

  • 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还有剩余字符,仍然视为成功。想要完全匹配,可以在表达式末尾加上边界匹配符'$'。 

示例参见2.1小节。 

  • 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时指定匹配模式。 

复制代码
import re

# 将正则表达式编译成Pattern对象
pattern = re.compile(r'world')

# 使用search()查找匹配的子串,不存在能匹配的子串时将返回None
# 这个例子中使用match()无法成功匹配
match = pattern.search('hello world!')

if match:
    # 使用Match获得分组信息
    print(match.group())
复制代码

输出

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

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

import re

p = re.compile(r'd+')
print(p.split('one1two2three3four4'))

输出

['one', 'two', 'three', 'four', '']
  • findall(string[, pos[, endpos]]) | re.findall(pattern, string[, flags]): 

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

import re

p = re.compile(r'd+')
print(p.findall('one1two2three3four4'))

输出

['1', '2', '3', '4']
  • finditer(string[, pos[, endpos]]) | re.finditer(pattern, string[, flags]): 

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

import re

p = re.compile(r'd+')
for m in p.finditer('one1two2three3four4'):
    print(m.group(),)

输出

1
2
3
4
  • sub(repl, string[, count]) | re.sub(pattern, repl, string[, count]): 

使用repl替换string中每一个匹配的子串后返回替换后的字符串。 
当repl是一个字符串时,可以使用id或g<id>、g<name>引用分组,但不能使用编号0。 
当repl是一个方法时,这个方法应当只接受一个参数(Match对象),并返回一个字符串用于替换(返回的字符串中不能再引用分组)。 
count用于指定最多替换次数,不指定时全部替换。 

复制代码
import re

p = re.compile(r'(w+) (w+)')
s = 'i say, hello world!'

print(p.sub(r'2 1', s))

def func(m):
    return m.group(1).title() + ' ' + m.group(2).title()

print(p.sub(func, s))
复制代码

输出

say i, world hello!
I Say, Hello World!
  • subn(repl, string[, count]) |re.sub(pattern, repl, string[, count]): 

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

复制代码
import re

p = re.compile(r'(w+) (w+)')
s = 'i say, hello world!'

print(p.subn(r'2 1', s))

def func(m):
    return m.group(1).title() + ' ' + m.group(2).title()

print(p.subn(func, s))
复制代码
('say i, world hello!', 2)
('I Say, Hello World!', 2)
  • re.compile(strPattern[, flag]): 

这个方法是Pattern类的工厂方法,用于将字符串形式的正则表达式编译为Pattern对象。 第二个参数flag是匹配模式,取值可以使用按位或运算符'|'表示同时生效,比如re.I | re.M。另外,你也可以在regex字符串中指定模式,比如re.compile('pattern', re.I | re.M)与re.compile('(?im)pattern')是等价的。 
可选值有: 

  • re.I(re.IGNORECASE): 忽略大小写(括号内是完整写法,下同) 
  • M(MULTILINE): 多行模式,改变'^'和'$'的行为(参见上图) 
  • S(DOTALL): 点任意匹配模式,改变'.'的行为 
  • L(LOCALE): 使预定字符类 w W  B s S 取决于当前区域设定 
  • U(UNICODE): 使预定字符类 w W  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中的正则表达式元字符如*/+/?等之前加上转义符再返回,在需要大量匹配元字符时有那么一点用。

6.举例常用的匹配方式

  • w与W
import re
print(re.findall('w','hello hexin 123'))
print(re.findall('W','hello hexin 123'))

输出

['h', 'e', 'l', 'l', 'o', 'h', 'e', 'x', 'i', 'n', '1', '2', '3']
[' ', ' ']
  • s与S
import re
print(re.findall('s','hello  hexin  123'))
print(re.findall('S','hello  hexin  123'))

输出

[' ', ' ', ' ', ' ']
['h', 'e', 'l', 'l', 'o', 'h', 'e', 'x', 'i', 'n', '1', '2', '3']
  • d与D
import re
print(re.findall('d','hello hexin 123'))
print(re.findall('D','hello hexin 123'))

输出

['1', '2', '3']
['h', 'e', 'l', 'l', 'o', ' ', 'h', 'e', 'x', 'i', 'n', ' ']
  • A与
import re
print(re.findall('Ahe','hello hexin 123'))
print(re.findall('123','hello hexin 123'))

输出

['he']
['123']
import re
print(re.findall(r'
','hello hexin 
123'))
print(re.findall(r'	','hello heixn 	123'))

输出

['
']
['	']
  • ^与$
import re
print(re.findall('^h','hello hexin 123'))
print(re.findall('3$','hello hexin 123')) 

输出

['h']
['3']

  • 重复匹配:| . | * | ? | .* | .*? | + | {n,m} |
print(re.findall('a.b','a1b'))
print(re.findall('a.b','a
b'))
print(re.findall('a.b','a
b',re.S))
print(re.findall('a.b','a
b',re.DOTALL)) 

输出

['a1b']
[]
['a
b']
['a
b']
  • *
import re
print(re.findall('ab*','bbbbbbb'))
print(re.findall('ab*','a')) 

输出

[]
['a']
import re
print(re.findall('ab?','a'))
print(re.findall('ab?','abbb')) 

输出

['a']
['ab']
  • 匹配所有包含小数在内的数字
import re
print(re.findall('d+.?d*',"asdfasdf123as1.13dfa12adsf1asdf3"))

输出

['123', '1.13', '12', '1', '3']
  • .*默认为贪婪匹配
print(re.findall('a.*b','a1b22222222b'))

输出

['a1b22222222b']
  • .*?为非贪婪匹配
import re
print(re.findall('a.*?b','a1b22222222b'))

 输出

['a1b']
  • +
import re
print(re.findall('ab+','a')) 
print(re.findall('ab+','abbb'))

输出

[]
['abbb']
  • {n,m}
import re
print(re.findall('ab{2}','abbb'))
print(re.findall('ab{2,4}','abbb'))
print(re.findall('ab{1,}','abbb'))
print(re.findall('ab{0,}','abbb')) 

输出

['abb']
['abbb']
['abbb']
['abbb']
  • []
import re
print(re.findall('a[1*-]b','a1b a*b a-b')) #[]内的都为普通字符了,且如果-没有被转意的话,应该放到[]的开头或结尾
print(re.findall('a[^1*-]b','a1b a*b a-b a=b')) #[]内的^代表的意思是取反
print(re.findall('a[0-9]b','a1b a*b a-b a=b')) #[]内的^代表的意思是取反
print(re.findall('a[a-z]b','a1b a*b a-b a=b aeb')) #[]内的^代表的意思是取反
print(re.findall('a[a-zA-Z]b','a1b a*b a-b a=b aeb aEb')) #[]内的^代表的意思是取反

输出

['a1b', 'a*b', 'a-b']
['a=b']
['a1b']
['aeb']
['aeb', 'aEb']
  • ()
import re
print(re.findall('ab+','ababab123'))
print(re.findall('(ab)+123','ababab123')) #匹配到末尾的ab123中的ab
print(re.findall('(?:ab)+123','ababab123')) #findall的结果不是匹配的全部内容,而是组内的内容,?:可以让结果为匹配的全部内容

输出

['ab', 'ab', 'ab']
['ab']
['ababab123']
print(re.findall('a\c','ac')) #对于正则来说a\c确实可以匹配到ac,但是在python解释器读取a\c时,会发生转义,然后交给re去执行,所以抛出异常
print(re.findall(r'a\c','ac')) #r代表告诉解释器使用rawstring,即原生字符串,把我们正则内的所有符号都当普通字符处理,不要转义
print(re.findall('a\\c','ac')) #同上面的意思一样,和上面的结果一样都是['a\c']

输出

[]
['a\c']
['a\c']
  • |
import re
print(re.findall('compan(y|ies)','Too many companies have gone bankrupt, and the next one is my company'))

print(re.findall('compan(?:y|ies)','Too many companies have gone bankrupt, and the next one is my company'))    #(?:)匹配完整

输出

['ies', 'y']
['companies', 'company']

补充:

数字匹配

复制代码
import re

print(re.findall(r'-?d+.?d*',"1-12*(60+(-40.35/5)-(-4*3))")) #找出所有数字['1', '-12', '60', '-40.35', '5', '-4', '3']


#使用|,先匹配的先生效,|左边是匹配小数,而findall最终结果是查看分组,所有即使匹配成功小数也不会存入结果
#而不是小数时,就去匹配(-?d+),匹配到的自然就是,非小数的数,在此处即整数
print(re.findall(r"-?d+.d*|(-?d+)","1-2*(60+(-40.35/5)-(-4*3))")) #找出所有整数['1', '-2', '60', '', '5', '-4', '3']
复制代码

总结:
 尽量使用泛匹配模式.*
 尽量使用非贪婪模式:.*?
 使用括号得到匹配目标:用group(n)去取得结果
 有换行符就用re.S:修改模式

模块简单使用

复制代码
import re
#1
print(re.findall('e','he make love') )   #['e', 'e', 'e'],返回所有满足匹配条件的结果,放在列表里
#2
print(re.search('e','he make love').group()) #e,只到找到第一个匹配然后返回一个包含匹配信息的对象,该对象可以通过调用group()方法得到匹配的字符串,如果字符串没有匹配,则返回None。

#3
print(re.match('e','he make love'))    #None,同search,不过在字符串开始处进行匹配,完全可以用search+^代替match

#4
print(re.split('[ab]','abcd'))     #['', '', 'cd'],先按'a'分割得到''和'bcd',再对''和'bcd'分别按'b'分割

#5
print('===>',re.sub('a','A','he make love')) #===> he mAke love,不指定n,默认替换所有
print('===>',re.sub('a','A','he make love',1)) #===> he mAke love
print('===>',re.sub('a','A','he make love',2)) #===> he mAke love
print('===>',re.sub('^(w+)(.*?s)(w+)(.*?s)(w+)(.*?)$',r'52341','he make love')) #===> love make he

print('===>',re.subn('a','A','he make love')) #===> ('he mAke love', 2),结果带有总共替换的个数


#6
obj=re.compile('d{2}')

print(obj.search('abc123eeee').group()) #12
print(obj.findall('abc123eeee')) #['12'],重用了obj
复制代码

输出

复制代码
['e', 'e', 'e']
e
None
['', '', 'cd']
===> he mAke love
===> he mAke love
===> he mAke love
===> love make he
===> ('he mAke love', 1)
12
['12']
复制代码

 

原文地址:https://www.cnblogs.com/zhangyingai/p/7098003.html