正则表达式的大致匹配过程是:
依次拿出表达式和文本中的字符比较,如果每一个字符都能匹配,则匹配成功;
一旦有匹配不成功的字符则匹配失败。如果表达式中有量词或边界,这个过程会稍微有一些不同,但也是很好理解的,
看下图中的示例以及自己多使用几次就能明白。
下图列出了Python支持的正则表达式元字符和语法:

Python 自带了re模块,它提供了对正则表达式的支持。主要用到的方法列举如下
1 2 3 4 5 6 7 8 9 10 |
#返回pattern对象 re.compile(string[,flag]) #以下为匹配所用函数 re.match(pattern, string[, flags]) re.search(pattern, string[, flags]) re.split(pattern, string[, maxsplit]) re.findall(pattern, string[, flags]) re.finditer(pattern, string[, flags]) re.sub(pattern, repl, string[, count]) re.subn(pattern, repl, string[, count]) |
Pattern概念: Pattern是一个匹配模式,那么我们怎么获得这个匹配模式呢?很简单,我们需要利用re.compile方法就可以。例如
[code]
Pattern = re.compile(r'hello')
另外大家可能注意到了另一个参数 flags,在这里解释一下这个参数的含义:
1 2 3 4 5 6 |
• 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): 详细模式。这个模式下正则表达式可以是多行,忽略空白字符,并可以加入注释。 |
注:以下七个方法中的flags同样是代表匹配模式的意思,如果在pattern生成时已经指明了flags,那么在下面的方法中就不需要传入这个参数了。
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 |
# -*- coding: utf-8 -*- __author__ = 'songhao' # 导入re 模块 import re # 将正则表达式编译成Pattern 对象,注意hello前面的r代表的raw,原生字符的意思 pattern = re.compile(r"hello") result1 = pattern.match('hello') result2 = pattern.match('hello kkk') result3 = pattern.match('hell') if result1: print(result1.group()) else: print("result1匹配失败") if result2: print(result2.group()) else: print("result2 匹配失败") if result3: print(result3.groupdict()) else: print("result3 匹配失败") ###out### #hello #hello #result3 匹配失败 |
"""
属性: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。"""
一个简单的re.match例子
1 2 3 4 5 6 7 8 9 10 11 12 13 |
# -*- coding: utf-8 -*- __author__ = 'songhao' import re # 一个简单的match实例 m = re.match(r'(\w+) (\w+)(?P<other>.*)', "hello world%") print("m.string", m.string) print("m.re", m.re) print('m.pos', m.pos) print('m.endpos', m.endpos) print('m.group', m.group()) print('m.groupdict', m.groupdict()) print(r"m.expand(r'\g \g\g'):", m.expand(r'\2 \1\3')) |

re.sub(pattern, repl, string[, count])
使用repl替换string中每一个匹配的子串后返回替换后的字符串。
当repl是一个字符串时,可以使用\id或\g、\g引用分组,但不能使用编号0。
当repl是一个方法时,这个方法应当只接受一个参数(Match对象),并返回一个字符串用于替换(返回的字符串中不能再引用分组)。
count用于指定最多替换次数,不指定时全部替换。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
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! |
