本文以例子的形势,介绍如何在python中使用正则表达式。
Example1
#!/usr/bin/python
import re
import sys
pattern = re.compile(r'[a-zA-Z]+\s+[0-9]+')
match = pattern.match(u"ni 12222")
print match
if match:
print match.group()
output:
ni 12222
re.match用法
re.match(pattern, string, flags=0)
参数
- patten : 正则表达式
- string: 要匹配的表达式
- flags: 标志位,用于控制正则表达式的匹配方式,如:是否区分大小写,多行匹配等等,可参考http://www.runoob.com/python/python-reg-expressions.html#flags
返回值
匹配成功re.match方法返回一个匹配的对象,否则返回None。
可以使用group或groups等函数查看匹配结果。
group([group1, …]):
获得一个或多个分组截获的字符串;指定多个参数时将以元组形式返回。group1可以使用编号也可以使用别名;编号0代表整个匹配的子串;不填写参数时,返回group(0);没有截获字符串的组返回None;截获了多次的组返回最后一次截获的子串。groups([default]):
以元组形式返回全部分组截获的字符串。相当于调用group(1,2,…last)。default表示没有截获字符串的组以这个值替代,默认为None。
Example2
#!/usr/bin/python
# -*- coding: utf-8 ------*-------
import re
import sys
pattern = re.compile(r'([a-zA-Z]+)\s+([0-9]+)')
match = pattern.match(u"ni 12222")
print match
if match:
print "group():", match.group()
print "group(1):", match.group(1)
print "group(2)", match.group(2)
print "groups()", match.groups()
output:
group():ni 12222
group(1):ni
group(2):12222
groups():(u’ni’, u’12222’)
re.match与re.search的区别
re.search参数和使用方法同re.match。
其区别是:
re.match只匹配字符串的开始,如果字符串开始不符合正则表达式,则匹配失败,函数返回None;而re.search匹配整个字符串,直到找到一个匹配。
参考
http://www.runoob.com/python/python-reg-expressions.html
https://www.cnblogs.com/huxi/archive/2010/07/04/1771073.html