正则表达式并非Python的一部分。正则表达式是用于处理字符串的强大工具,拥有本身独特的语法以及一个独立的处理引擎,效率上可能不如str自带的方法,但功能十分强大。得益于这一点,在提供了正则表达式的语言里,正则表达式的语法都是同样的,区别只在于不一样的编程语言实现支持的语法数量不一样;但不用担忧,不被支持的语法一般是不经常使用的部分。若是已经在其余语言里使用过正则表达式,只须要简单看一看就能够上手了。html
下图展现了使用正则表达式进行匹配的流程: git
正则表达式的大体匹配过程是:依次拿出表达式和文本中的字符比较,若是每个字符都能匹配,则匹配成功;一旦有匹配不成功的字符则匹配失败。若是表达式中有量词或边界,这个过程会稍微有一些不一样,但也是很好理解的,看下图中的示例以及本身多使用几回就能明白。程序员
下图列出了Python支持的正则表达式元字符和语法: 正则表达式
正则表达式一般用于在文本中查找匹配的字符串。Python里数量词默认是贪婪的(在少数语言里也多是默认非贪婪),老是尝试匹配尽量多的字符;非贪婪的则相反,老是尝试匹配尽量少的字符。例如:正则表达式"ab*"若是用于查找"abbbc",将找到"abbb"。而若是使用非贪婪的数量词"ab*?",将找到"a"。编程
与大多数编程语言相同,正则表达式里使用"\"做为转义字符,这就可能形成反斜杠困扰。假如你须要匹配文本中的字符"\",那么使用编程语言表示的正则表达式里将须要4个反斜杠"\\\\":前两个和后两个分别用于在编程语言里转义成反斜杠,转换成两个反斜杠后再在正则表达式里转义成一个反斜杠。Python里的原生字符串很好地解决了这个问题,这个例子中的正则表达式可使用r"\\"表示。一样,匹配一个数字的"\\d"能够写成r"\d"。有了原生字符串,你不再用担忧是否是漏写了反斜杠,写出来的表达式也更直观。编程语言
正则表达式提供了一些可用的匹配模式,好比忽略大小写、多行匹配等,这部份内容将在Pattern类的工厂方法re.compile(pattern[, flags])中一块儿介绍。工具
Python经过re模块提供对正则表达式的支持。使用re的通常步骤是先将正则表达式的字符串形式编译为Pattern实例,而后使用Pattern实例处理文本并得到匹配结果(一个Match实例),最后使用Match实例得到信息,进行其余的操做。spa
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
# encoding: UTF-8
import
re
# 将正则表达式编译成Pattern对象
pattern
=
re.
compile
(r
'hello'
)
# 使用Pattern匹配文本,得到匹配结果,没法匹配时将返回None
match
=
pattern.match(
'hello world!'
)
if
match:
# 使用Match得到分组信息
print
match.group()
### 输出 ###
# hello
|
re.compile(strPattern[, flag]):3d
这个方法是Pattern类的工厂方法,用于将字符串形式的正则表达式编译为Pattern对象。 第二个参数flag是匹配模式,取值可使用按位或运算符'|'表示同时生效,好比re.I | re.M。另外,你也能够在regex字符串中指定模式,好比re.compile('pattern', re.I | re.M)与re.compile('(?im)pattern')是等价的。
可选值有:code
1
2
3
4
|
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类的实例方法部分一块儿介绍。如上面这个例子能够简写为:
1
2
|
m
=
re.match(r
'hello'
,
'hello world!'
)
print
m.group()
|
re模块还提供了一个方法escape(string),用于将string中的正则表达式元字符如*/+/?等以前加上转义符再返回,在须要大量匹配元字符时有那么一点用。
Match对象是一次匹配的结果,包含了不少关于这次匹配的信息,可使用Match提供的可读属性或方法来获取这些信息。
属性:
方法:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
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 \1\3'):"
, m.expand(r
'\2 \1\3'
)
### output ###
# m.string: hello world!
# m.re: <_sre.SRE_Pattern object at 0x016E1A38>
# 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!
|
Pattern对象是一个编译好的正则表达式,经过Pattern提供的一系列方法能够对文本进行匹配查找。
Pattern不能直接实例化,必须使用re.compile()进行构造。
Pattern提供了几个可读属性用于获取表达式的相关信息:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
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
### output ###
# p.pattern: (\w+) (\w+)(?P<sign>.*)
# p.flags: 16
# p.groups: 3
# p.groupindex: {'sign': 3}
|
实例方法[ | re模块方法]:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
# encoding: UTF-8
import
re
# 将正则表达式编译成Pattern对象
pattern
=
re.
compile
(r
'world'
)
# 使用search()查找匹配的子串,不存在能匹配的子串时将返回None
# 这个例子中使用match()没法成功匹配
match
=
pattern.search(
'hello world!'
)
if
match:
# 使用Match得到分组信息
print
match.group()
### 输出 ###
# world
|
1
2
3
4
5
6
7
|
import
re
p
=
re.
compile
(r
'\d+'
)
print
p.split(
'one1two2three3four4'
)
### output ###
# ['one', 'two', 'three', 'four', '']
|
1
2
3
4
5
6
7
|
import
re
p
=
re.
compile
(r
'\d+'
)
print
p.findall(
'one1two2three3four4'
)
### output ###
# ['1', '2', '3', '4']
|
1
2
3
4
5
6
7
8
|
import
re
p
=
re.
compile
(r
'\d+'
)
for
m
in
p.finditer(
'one1two2three3four4'
):
print
m.group(),
### output ###
# 1 2 3 4
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
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)
### output ###
# say i, world hello!
# I Say, Hello World!
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
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)
### output ###
# ('say i, world hello!', 2)
# ('I Say, Hello World!', 2)
|
以上就是Python对于正则表达式的支持。熟练掌握正则表达式是每个程序员必须具有的技能,这年头没有不与字符串打交道的程序了。笔者也处于初级阶段,与君共勉,^_^
另外,图中的特殊构造部分没有举出例子,用到这些的正则表达式是具备必定难度的。有兴趣能够思考一下,如何匹配不是以abc开头的单词,^_^
转自:http://www.cnblogs.com/huxi/archive/2010/07/04/1771073.html