Home  >  Article  >  Backend Development  >  理解python正则表达式

理解python正则表达式

WBOY
WBOYOriginal
2016-06-10 15:06:401055browse

在python中,对正则表达式的支持是通过re模块来支持的。使用re的步骤是先把表达式字符串编译成pattern实例,然后在使用pattern去匹配文本获取结果。

其实也有另外一种方式,就是直接使用re模块的方法,但是这样就不能使用编译后的pattern实例了。

实例:

#!/usr/bin/python
# -*- coding: utf-8 -*-

import re

pat = re.compile(r'hello')

match = pat.match('hello world!')

if match:
  print match.group()

match1 = re.match(r'hello','hello world!')

if match1:
  print match1.group()

  print match1.pos

返回的结果相同,都是 hello

关于Pattern 对象:

它是由re.complie函数来构造的,是一个编译好的正则表达式,通过Pattern提供的一系列方法可以对文本进行匹配查找。

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

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

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

关于 re.compile方法

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 \B \s \S 取决于当前区域设定
  • U(UNICODE): 使预定字符类 \w \W \b \B \s \S \d \D 取决于unicode定义的字符属性
  • X(VERBOSE): 详细模式。这个模式下正则表达式可以是多行,忽略空白字符,并可以加入注释

1).关于 match方法:

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

属性:

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

方法:

1、group([group1, …]):
获得一个或多个分组截获的字符串;指定多个参数时将以元组形式返回。group1可以使用编号也可以使用别名;编号0代表整个匹配的子串;不填写参数时,返回group(0);没有截获字符串的组返回None;截获了多次的组返回最后一次截获的子串。
2、groups([default]):
以元组形式返回全部分组截获的字符串。相当于调用group(1,2,…last)。default表示没有截获字符串的组以这个值替代,默认为None。
3、groupdict([default]):
返回以有别名的组的别名为键、以该组截获的子串为值的字典,没有别名的组不包含在内。default含义同上。
4、start([group]):
返回指定的组截获的子串在string中的起始索引(子串第一个字符的索引)。group默认值为0。
5、end([group]):
返回指定的组截获的子串在string中的结束索引(子串最后一个字符的索引+1)。group默认值为0。
6、span([group]):
返回(start(group), end(group))。
7、expand(template):
将匹配到的分组代入template中然后返回。template中可以使用\id或\g、\g引用分组,但不能使用编号0。\id与\g是等价的;但\10将被认为是第10个分组,如果你想表达\1之后是字符'0',只能使用\g0。
请看例子:

#!/usr/bin/python
# -*- coding: utf-8 -*-

import re

m = re.match(r'(\w+)\s(\w+)','aaa bbb ccc')

print m.string

print m.re

print m.pos

print m.endpos

print m.lastindex

print m.lastgroup

print m.group()

print m.start()

print m.end()

print m.span()

print m.expand(r'\2 \1')

结果为:

aaa bbb ccc
<_sre.sre_pattern object at>
0
11
2
None
aaa bbb
0
7
(0, 7)
bbb aaa

2).关于search方法:

  查找可以匹配的子串,和match 不同的是他不是从开始处开始匹配的。如果没有匹配上,则返回None

上面的例子中,将match 换成search返回的结果一样

请看:

#!/usr/bin/python
# -*- coding: utf-8 -*-

import re

pat = re.compile(r'hello')

match = pat.match('shello world!')

if match:
  print match.group()
else:
  print 'not match!'

match1 = re.search(r'hello','shello world!')

if match1:
  print match1.group()

结果为:

not match!
hello

这2个函数,没有其他区别,就是一个是从开始匹配的,另外一个不是开始的

3.split(string[, maxsplit]) | re.split(pattern, string[, maxsplit]):
按照能够匹配的子串将string分割后返回列表。maxsplit用于指定最大分割次数,不指定将全部分割。

4.findall(string[, pos[, endpos]]) | re.findall(pattern, string[, flags]):
搜索string,以列表形式返回全部能匹配的子串。

5.finditer(string[, pos[, endpos]]) | re.finditer(pattern, string[, flags]):
搜索string,返回一个顺序访问每一个匹配结果(Match对象)的迭代器。

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

7.subn(repl, string[, count]) |re.sub(pattern, repl, string[, count]):
返回 (sub(repl, string[, count]), 替换次数)。

例子为:

#!/usr/bin/python
# -*- coding: utf-8 -*-

import re

p =re.compile(r'\d+')

print p.split('aa1bb2cc3dd4ee5ff6')

print p.findall('aa1bb2cc3dd4ee5ff6')

for m in p.finditer('aa1bb2cc3dd4ee5ff6'):
  print m.group(),

print '\nsub test'
p1 =re.compile(r'(\w+)\s+(\w+)')

s = 'i am ok'

print p1.sub(r'\2 \1',s)
print p1.subn(r'\2 \1',s)

结果:

['aa', 'bb', 'cc', 'dd', 'ee', 'ff', '']
['1', '2', '3', '4', '5', '6']
1 2 3 4 5 6
sub test
am i ok
('am i ok', 1)

以上就是本文的全部内容,希望对大家的学习有所帮助。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn