正则表达式
正则表达式
正则表达式(regular expression)是可以匹配文本片段的模式。最简单的正则表达式就是普通字符串,可以匹配其自身。比如,正则表达式 ‘hello’ 可以匹配字符串 ‘hello’。要注意的是,正则表达式并不是一个程序,而是用于处理字符串的一种模式,如果你想用它来处理字符串,就必须使用支持正则表达式的工具,比如
在\
对特殊字符进行转义,比如,为了匹配字符串 ‘python.org’,我们需要使用正则表达式 'python\.org'
,而\
转义,所以上面的正则表达式在'python\\.org'
,这会很容易陷入 \
的困扰中,因此,我们建议使用
r'python\.org'
compile 函数match 函数search 函数findall 函数finditer 函数split 函数sub 函数subn 函数
- 使用
compile 函数将正则表达式的字符串形式编译为一个Pattern 对象 - 通过
Pattern 对象提供的一系列方法对文本进行匹配查找,获得匹配结果(一个Match 对象) - 最后使用
Match 对象提供的属性和方法获得信息,根据需要进行其他的操作
Pattern
compile 函数
re.compile(pattern[, flag])
其中,
import re
# 将正则表达式编译成 Pattern 对象
pattern = re.compile(r'\d+')
match 方法
match(string[, pos[, endpos]])
其中,
当匹配成功时,返回一个
看看例子。
>>> import re
>>> pattern = re.compile(r'\d+') # 用于匹配至少一个数字
>>> m = pattern.match('one12twothree34four') # 查找头部,没有匹配
>>> print m
None
>>> m = pattern.match('one12twothree34four', 2, 10) # 从'e'的位置开始匹配,没有匹配
>>> print m
None
>>> m = pattern.match('one12twothree34four', 3, 10) # 从'1'的位置开始匹配,正好匹配
>>> print m # 返回一个 Match 对象
<_sre.SRE_Match object at 0x10a42aac0>
>>> m.group(0) # 可省略 0
'12'
>>> m.start(0) # 可省略 0
3
>>> m.end(0) # 可省略 0
5
>>> m.span(0) # 可省略 0
(3, 5)
在上面,当匹配成功时返回一个
group([group1, …])
方法用于获得一个或多个分组匹配的字符串,当要获得整个匹配的子串时,可直接使用group()
或group(0)
;start([group])
方法用于获取分组匹配的子串在整个字符串中的起始位置(子串第一个字符的索引) ,参数默认值为0 ;end([group])
方法用于获取分组匹配的子串在整个字符串中的结束位置(子串最后一个字符的索引+1 ) ,参数默认值为0 ;span([group])
方法返回(start(group), end(group))
。
再看看一个例子:
>>> import re
>>> pattern = re.compile(r'([a-z]+) ([a-z]+)', re.I) # re.I 表示忽略大小写
>>> m = pattern.match('Hello World Wide Web')
>>> print m # 匹配成功,返回一个 Match 对象
<_sre.SRE_Match object at 0x10bea83e8>
>>> m.group(0) # 返回匹配成功的整个子串
'Hello World'
>>> m.span(0) # 返回匹配成功的整个子串的索引
(0, 11)
>>> m.group(1) # 返回第一个分组匹配成功的子串
'Hello'
>>> m.span(1) # 返回第一个分组匹配成功的子串的索引
(0, 5)
>>> m.group(2) # 返回第二个分组匹配成功的子串
'World'
>>> m.span(2) # 返回第二个分组匹配成功的子串
(6, 11)
>>> m.groups() # 等价于 (m.group(1), m.group(2), ...)
('Hello', 'World')
>>> m.group(3) # 不存在第三个分组
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: no such group
search 方法
search(string[, pos[, endpos]])
其中,
当匹配成功时,返回一个
让我们看看例子:
>>> import re
>>> pattern = re.compile('\d+')
>>> m = pattern.search('one12twothree34four') # 这里如果使用 match 方法则不匹配
>>> m
<_sre.SRE_Match object at 0x10cc03ac0>
>>> m.group()
'12'
>>> m = pattern.search('one12twothree34four', 10, 30) # 指定字符串区间
>>> m
<_sre.SRE_Match object at 0x10cc03b28>
>>> m.group()
'34'
>>> m.span()
(13, 15)
再来看一个例子:
# -*- coding: utf-8 -*-
import re
# 将正则表达式编译成 Pattern 对象
pattern = re.compile(r'\d+')
# 使用 search() 查找匹配的子串,不存在匹配的子串时将返回 None
# 这里使用 match() 无法成功匹配
m = pattern.search('hello 123456 789')
if m:
# 使用 Match 获得分组信息
print 'matching string:',m.group()
print 'position:',m.span()
执行结果:
matching string: 123456
position: (6, 12)
findall 方法
上面的
findall(string[, pos[, endpos]])
其中,
import re
pattern = re.compile(r'\d+') # 查找数字
result1 = pattern.findall('hello 123456 789')
result2 = pattern.findall('one1two2three3four4', 0, 10)
print result1
print result2
执行结果:
['123456', '789']
['1', '2']
finditer 方法
# -*- coding: utf-8 -*-
import re
pattern = re.compile(r'\d+')
result_iter1 = pattern.finditer('hello 123456 789')
result_iter2 = pattern.finditer('one1two2three3four4', 0, 10)
print type(result_iter1)
print type(result_iter2)
print 'result1...'
for m1 in result_iter1: # m1 是 Match 对象
print 'matching string: {}, position: {}'.format(m1.group(), m1.span())
print 'result2...'
for m2 in result_iter2:
print 'matching string: {}, position: {}'.format(m2.group(), m2.span())
执行结果:
<type 'callable-iterator'>
<type 'callable-iterator'>
result1...
matching string: 123456, position: (6, 12)
matching string: 789, position: (13, 16)
result2...
matching string: 1, position: (3, 4)
matching string: 2, position: (7, 8)
split 方法
split(string[, maxsplit])
其中,
import re
p = re.compile(r'[\s\,\;]+')
print p.split('a,b;; c d')
执行结果:
['a', 'b', 'c', 'd']
sub 方法
sub(repl, string[, count])
其中,
- 如果
repl 是字符串,则会使用repl 去替换字符串每一个匹配的子串,并返回替换后的字符串,另外,repl 还可以使用\id
的形式来引用分组,但不能使用编号0 ; - 如果
repl 是函数,这个方法应当只接受一个参数(Match 对象) ,并返回一个字符串用于替换(返回的字符串中不能再引用分组) 。
import re
p = re.compile(r'(\w+) (\w+)')
s = 'hello 123, hello 456'
def func(m):
return 'hi' + ' ' + m.group(2)
print p.sub(r'hello world', s) # 使用 'hello world' 替换 'hello 123' 和 'hello 456'
print p.sub(r'\2 \1', s) # 引用分组
print p.sub(func, s)
print p.sub(func, s, 1) # 最多替换一次
执行结果:
hello world, hello world
123 hello, 456 hello
hi 123, hi 456
hi 123, hello 456
subn 方法
subn(repl, string[, count])
它返回一个元组:
(sub(repl, string[, count]), 替换次数)
元组有两个元素,第一个元素是使用
import re
p = re.compile(r'(\w+) (\w+)')
s = 'hello 123, hello 456'
def func(m):
return 'hi' + ' ' + m.group(2)
print p.subn(r'hello world', s)
print p.subn(r'\2 \1', s)
print p.subn(func, s)
print p.subn(func, s, 1)
执行结果:
('hello world, hello world', 2)
('123 hello, 456 hello', 2)
('hi 123, hi 456', 2)
('hi 123, hello 456', 1)
其他函数
事实上,使用
match 函数
re.match(pattern, string[, flags]):
其中,\d+
[a-z]+
。而
match(string[, pos[, endpos]])
可以看到,
import re
m1 = re.match(r'\d+', 'One12twothree34four')
if m1:
print 'matching string:',m1.group()
else:
print 'm1 is:',m1
m2 = re.match(r'\d+', '12twothree34four')
if m2:
print 'matching string:', m2.group()
else:
print 'm2 is:',m2
执行结果:
m1 is: None
matching string: 12
search 函数
re.search(pattern, string[, flags])
findall 函数
re.findall(pattern, string[, flags])
import re
print re.findall(r'\d+', 'hello 12345 789')
# 输出
['12345', '789']
finditer 函数
re.finditer(pattern, string[, flags])
split 函数
re.split(pattern, string[, maxsplit])
sub 函数
re.sub(pattern, repl, string[, count])
subn 函数
re.subn(pattern, repl, string[, count])
到底用哪种方式
从上文可以看到,使用
- 使用
re.compile 函数生成一个Pattern 对象,然后使用Pattern 对象的一系列方法对文本进行匹配查找; - 直接使用
re.match, re.search 和re.findall 等函数直接对文本匹配查找;
下面,我们用一个例子展示这两种方法。先看第
import re
# 将正则表达式先编译成 Pattern 对象
pattern = re.compile(r'\d+')
print pattern.match('123, 123')
print pattern.search('234, 234')
print pattern.findall('345, 345')
再看第
import re
print re.match(r'\d+', '123, 123')
print re.search(r'\d+', '234, 234')
print re.findall(r'\d+', '345, 345')
如果一个正则表达式需要用到多次(比如上面的 \d+
匹配中文
在某些情况下,我们想匹配文本中的汉字,有一点需要注意的是,中文的[\u4e00-\u9fa5]
,这里说主要是因为这个范围并不完整,比如没有包括全角(中文)标点,不过,在大部分情况下,应该是够用的。假设现在想把字符串 title = u'你好,hello,世界'
中的中文提取出来,可以这么做:
# -*- coding: utf-8 -*-
import re
title = u'你好,hello,世界'
pattern = re.compile(ur'[\u4e00-\u9fa5]+')
result = pattern.findall(title)
print result
注意到,我们在正则表达式前面加上了两个前缀 ur
,其中 r
表示使用原始字符串,u
表示是
执行结果
[u'\u4f60\u597d', u'\u4e16\u754c']
贪婪匹配
在div
块:
import re
content = 'aa<div>test1</div>bb<div>test2</div>cc'
pattern = re.compile(r'<div>.*</div>')
result = pattern.findall(content)
print result
执行结果:
['<div>test1</div>bb<div>test2</div>']
由于正则匹配是贪婪匹配,也就是尽可能多的匹配,因此,在成功匹配到第一个
import re
content = 'aa<div>test1</div>bb<div>test2</div>cc'
pattern = re.compile(r'<div>.*?</div>') # 加上 ?
result = pattern.findall(content)
print result
结果:
['<div>test1</div>', '<div>test2</div>']