码迷,mamicode.com
首页 > 编程语言 > 详细

Python中的正则表达式

时间:2015-10-26 22:12:47      阅读:373      评论:0      收藏:0      [点我收藏+]

标签:

一、正则表达式匹配规则

  下面是Python中正则表达式的一些匹配规则,图片资料来自CSDN:

技术分享

二、正则表达式相关注释

2.1 数量词的贪婪与非贪婪模式

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

正则表达式 目标字符串 贪婪模式匹配结果 非贪婪模式匹配结果
ab* abbbc abbb a

注:在爬虫脚本中一般采用非贪婪模式。

2.2 反斜杠问题

  在正则表达式中会用到反斜杠进行转义表达一些字符,如果要在正则表达式中表示反斜杠,在编程语言中需要表达为:“\\\\”,因为编程语言中写反斜杠也是需要转义的。使用Python原生字符串可以轻松表达,写成r"\\"即可。

三、Python中的正则表达式

  Python中的Re模块实现了对正则表达式的支持。主要方法接口为:

#返回pattern对象,这种对象表达了一种匹配模式
re.compile(string[,flag])  
#以下为匹配所用函数
re.match(pattern, string[, flags])    #从字符串开始处(仅从位置0开始)匹配,匹配不成功返回None
re.search(pattern, string[, flags])    #从字符串所有位置匹配,任意起点匹配成功均可
re.split(pattern, string[, maxsplit])   #按照pattern指定的模式匹配后分割出子字符串数组
re.findall(pattern, string[, flags])   #返回所有符合模式匹配的子字符串数组
re.finditer(pattern, string[, flags])   #返回所有符合模式匹配的子字符串的引用(迭代器)
re.sub(pattern, repl, string[, count])  #用repl替代string中符合模式匹配的子字符串,repl既可以是字符串也可以是单参数函数
re.subn(pattern, repl, string[, count])  #返回 (sub(repl, string[, count]), 替换次数),也就是比上一个函数多了一个“替换次数”

 3.1 pattern对象

  Re模块中的pattern对象表达了一种匹配内容与模式,第一个参数是必选的,也就是正则表达式字符串。第二个参数是可选的,表示匹配模式。匹配模式有很多种,可以用“|”进行组合同时使用。这些匹配模式参见下表:

re.I(全拼:IGNORECASE): 忽略大小写(括号内是完整写法,下同)
 • re.M(全拼:MULTILINE): 多行模式,改变^$的行为(参见上图)
 • re.S(全拼:DOTALL): 点任意匹配模式,改变.的行为
 • re.L(全拼:LOCALE): 使预定字符类 \w \W \b \B \s \S 取决于当前区域设定
 • re.U(全拼:UNICODE): 使预定字符类 \w \W \b \B \s \S \d \D 取决于unicode定义的字符属性
 • re.X(全拼:VERBOSE): 详细模式。这个模式下正则表达式可以是多行,忽略空白字符,并可以加入注释。

 3.2 re.match(pattern, string[, flags])

  这个方法将会从string(我们要匹配的字符串)的开头开始尝试匹配pattern(注意,如果第一个字符就匹配失败,该函数是不会在字符串中间进行匹配),一直向后匹配,如果遇到无法匹配的字符,立即返回 None,如果匹配未结束已经到达string的末尾,也会返回None。两个结果均表示匹配失败,否则匹配pattern成功,同时匹配终止,不再对 string向后匹配。下面我们通过一个例子理解一下:

# -*- coding: utf-8 -*-
 
#导入re模块
import re
 
# 将正则表达式编译成Pattern对象,注意hello前面的r的意思是“原生字符串”
pattern = re.compile(rhello)
 
# 使用re.match匹配文本,获得匹配结果,无法匹配时将返回None
result1 = re.match(pattern,hello)
result2 = re.match(pattern,helloo CQC!)
result3 = re.match(pattern,helo CQC!)
result4 = re.match(pattern,hello CQC!)
 
# 如果1匹配成功
if result1:
    # 使用Match获得分组信息
    print result1.group()
else:
    print 1匹配失败!

#如果2匹配失败
#...

#运行结果如下:
hello
hello
3匹配失败
hello

    在这个代码中打印的是result.group(),这是什么呢?这是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。

    方法包括如下:

技术分享
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。
View Code

  例子如下看看:

技术分享
# -*- coding: utf-8 -*-
#一个简单的match实例
 
import re
# 匹配如下内容:单词+空格+单词+任意字符
m = re.match(r(\w+) (\w+)(?P.*), 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():", m.group()
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‘\g \g\g‘):", m.expand(r\2 \1\3)
 
### output ###
# m.string: hello world!
# m.re: 
# 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 \1\3‘): world hello!
View Code

3.3 re.search(pattern, string[, flags])

  search方法与match方法极其类似,区别在于match()函数只检测re是不是在string的开始位置匹配,search()会扫描整个string查找匹配,match()只有在0位置匹配成功的话才有返回,如果不是开始位置匹配成功的话,match()就返回None。同样,search方法的返回对象同样match()返回对象的方法和属性。我们用一个例子感受一下:

技术分享
#导入re模块
import re
 
# 将正则表达式编译成Pattern对象
pattern = re.compile(rworld)
# 使用search()查找匹配的子串,不存在能匹配的子串时将返回None
# 这个例子中使用match()无法成功匹配
match = re.search(pattern,hello world!)
if match:
    # 使用Match获得分组信息
    print match.group()

### 输出 ###
# world
View Code

 3.4 re.split(pattern, string[, maxsplit])

  按照能够匹配的子串将string分割后返回列表。maxsplit用于指定最大分割次数,不指定将全部分割。我们通过下面的例子感受一下:

技术分享
import re
 
pattern = re.compile(r\d+)
print re.split(pattern,one1two2three3four4)
 
### 输出 ###
# [‘one‘, ‘two‘, ‘three‘, ‘four‘, ‘‘]
View Code

 3.5 re.findall(pattern, string[, flags])

   搜索string,以列表形式返回全部能匹配的子串。我们通过这个例子来感受一下:

技术分享
import re
 
pattern = re.compile(r\d+)
print re.findall(pattern,one1two2three3four4)
 
### 输出 ###
# [‘1‘, ‘2‘, ‘3‘, ‘4‘]
View Code

 3.6 re.finditer(pattern, string[, flags])

  搜索string,返回一个顺序访问每一个匹配结果(Match对象)的迭代器。我们通过下面的例子来感受一下:

技术分享
import re
 
pattern = re.compile(r\d+)
for m in re.finditer(pattern,one1two2three3four4):
    print m.group(),
 
### 输出 ###
# 1 2 3 4
View Code

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

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

技术分享
import re
 
pattern = re.compile(r(\w+) (\w+))
s = i say, hello world!
 
print re.sub(pattern,r\2 \1, s)
 
def func(m):
    return m.group(1).title() +   + m.group(2).title()
 
print re.sub(pattern,func, s)
 
### output ###
# say i, world hello!
# I Say, Hello World!
View Code

 3.8 re.subn(pattern, repl, string[, count])

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

技术分享
import re
 
pattern = re.compile(r(\w+) (\w+))
s = i say, hello world!
 
print re.subn(pattern,r\2 \1, s)
 
def func(m):
    return m.group(1).title() +   + m.group(2).title()
 
print re.subn(pattern,func, s)
 
### output ###
# (‘say i, world hello!‘, 2)
# (‘I Say, Hello World!‘, 2)
View Code

 备注:上述所有的用法其实可以直接用类似于pattern.match()的方式进行调用。这样就不需要把pattern作为第一个参数进行传入了,这是更方便的方式。

Python中的正则表达式

标签:

原文地址:http://www.cnblogs.com/kuliuheng/p/4912377.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!