Python正则表达式
正则表达式是一个特殊的字符序列,它能帮助你方便的检查一个字符串是否与某种模式匹配。
Python 自1.5版本起增加了re 模块,它提供 Perl 风格的正则表达式模式。
re 模块使 Python 语言拥有全部的正则表达式功能。
compile 函数根据一个模式字符串和可选的标志参数生成一个正则表达式对象。该对象拥有一系列方法用于正则表达式匹配和替换。
re 模块也提供了与这些方法功能完全一致的函数,这些函数使用一个模式字符串做为它们的第一个参数。
re.match函数
re.match 尝试从字符串的起始位置匹配一个模式,如果不是起始位置匹配成功的话,match()就返回none。
函数语法:
re.match(pattern, string, flags=0)
pattern:
匹配的正则表达式
string:要匹配的字符串。
flags:标志位,用于控制正则表达式的匹配方式,如:是否区分大小写,多行匹配等等。
匹配成功re.match方法返回一个匹配的对象,否则返回None。
我们可以使用group(num) 或 groups() 匹配对象函数来获取匹配表达式。
编程实例:
#coding UTF-8
import re
print(re.match("www","www.baidu.com").span())#在起始位置匹配
print(re.match("com","www.baidu.com"))#不在起始位置匹配
line="You are a good boy"
matchObj=re.match("(.*) are (.*?) .*",line,re.M|re.I)
if matchObj:
print "matchObj.group():",matchObj.group()
print "matchObj.group(1):",matchObj.group(1)
print "matchObj.group(2):",matchObj.group(2)
else:
print "No match!"
输出结果:
(0, 3)
None
matchObj.group(): You are a good boy
matchObj.group(1): You
matchObj.group(2): a
None
matchObj.group(): You are a good boy
matchObj.group(1): You
matchObj.group(2): a
re.search函数
re.search 扫描整个字符串并返回第一个成功的匹配。
函数语法:
re.search(pattern, string, flags=0)
参数这里就不说了,跟上面一样。
匹配成功re.search方法返回一个匹配的对象,否则返回None。
我们可以使用group(num) 或 groups() 匹配对象函数来获取匹配表达式。
#coding UTF-8
import re
print(re.search("www","www.baidu.com.www").span())
print(re.search("baidu","www.baidu.com").span())
line="You are a good boy"
searchObj = re.search( r'(.*) are (.*?) .*', line, re.M|re.I)
if searchObj:
print "searchObj.group() : ", searchObj.group()
print "searchObj.group(1) : ", searchObj.group(1)
print "searchObj.group(2) : ", searchObj.group(2)
else:
print "Nothing found!!"
输出结果:
(0, 3)
(4, 9)
searchObj.group() : You are a good boy
searchObj.group(1) : You
searchObj.group(2) : a