一、正则表达式简介
正则表达式用于文本匹配的工具,在源字符串中查找与给定的正则表达式相匹配的部分。一个正则表达式是由字母、数字和特殊字符组成的。正则表达式中有许多特殊的字符,这些特殊字符是构成正则表达式的要素。
1、正则表达式中的特殊字符:
2、正则表达式中的常用限定符:
利用{}可以控制字符重复的次数。
例如,\d{1,4}表示1位到3位的数字;
某些地区的电话号码是8位数,区号也有可能是3位或4位数字。
\d{3}-\d{8}|\d{4}-\d{7}
3、限定符与“?”的组合
二、使用sys.re模块处理正则表达式
Python的re模块具有正则表达式匹配的功能。re模块提供了一些根据正则表达式进行查找、替换、分隔字符串的函数,这些函数使用一个正则表达式作为第一个参数。
re模块常用的函数如下:
注意:
match()必须从字符串的第0个索引位置处开始搜索。如果第0个索引位置的字符不匹配,match()的匹配就会失败。
re模块的一些函数都有一个flags参数,该参数用于设置匹配的附加选项。例如,是否忽略大小写、是否支持多行匹配等。
re模块的规则选项
re模块定义了一些常量来表示这些选项,使用前导符号“re.”加选项的简写或名称的方式表示某个常量。例如,re.I或re.IGNORECASE表示忽略大小写。
正则表达式中有3种间隔符号:“^”、“$”和“\b”。
“^”匹配字符串首部的子串;
“$”匹配结束部分的子串;
“\b”用于分隔单词
例子:
#!/usr/bin/env python # -*- coding=utf-8 -*- #Using GPL v2.7 #Author: leexide@126.com #间隔符在Python中的使用方法 import re s = "HELLO WORLD" print re.findall(r"^hello",s) print re.findall(r"^hello",s,re.I) print re.findall("WORLD$",s) print re.findall(r"wORLD$",s,re.I) print re.findall(r"\b\w+\b",s)
输出结果:
---------- python2.7 ---------- [] ['HELLO'] ['WORLD'] ['WORLD'] ['HELLO', 'WORLD'] 输出完成 (耗时 0 秒) - 正常终止
例子:
使用re模块的sub()实现字符串的替代功能。
#!/usr/bin/env python # -*- coding=utf-8 -*- #Using GPL v2.7 #Author: leexide@126.com import re s = "hello world" print re.sub("hello","hi",s) print re.sub("hello","hi",s[-4:]) print re.sub("world","China",s[-5:])
输出结果:
---------- python2.7 ----------
hi world
orld
China
输出完成 (耗时 0 秒) - 正常终止
注意:
sub()先创建变量s的拷贝,然后在拷贝中替换字符串,并不会改变变量s的内容。
subn()功能与sub()相同,但是多返回1个值,即匹配后的替换次数。
例子:
subn()对字符串的替换以及正则表达式中特殊字符的使用方法。
#!/usr/bin/env python # -*- coding=utf-8 -*- #Using GPL v2.7 #Author: leexide@126.com # 特殊字符的使用 import re s = "你好 WORLD2" print "匹配字母数字:" + re.sub(r"\w", "hi", s) print "替换次数:" + str(re.subn(r"\w", "hi", s)[1]) print "匹配非字母数字的字符:" + re.sub(r"\W", "hi", s) print "替换次数:" + str(re.subn(r"\W", "hi", s)[1]) print "匹配空白字符:" + re.sub(r"\s", "*", s) print "替换次数:" + str(re.subn(r"\s", "*", s)[1]) print "匹配非空白字符:" + re.sub(r"\S", "hi", s) print "替换次数:" + str(re.subn(r"\S", "hi", s) [1]) print "匹配数字:" + re.sub(r"\d", "2.0", s) print "替换次数:" + str(re.subn(r"\d", "2.0", s)[1]) print "匹配非数字:" + re.sub(r"\D", "hi", s) print "替换次数:" + str(re.subn(r"\D", "hi", s)[1]) print "匹配任意字符:" + re.sub(r".", "hi", s) print "替换次数:" + str(re.subn(r".", "hi", s)[1])
输出结果:
---------- python2.7 ---------- 匹配字母数字:你好 hihihihihihi 替换次数:6 匹配非字母数字的字符:hihihihihiWORLD2 替换次数:5 匹配空白字符:你好*WORLD2 替换次数:1 匹配非空白字符:hihihihi hihihihihihi 替换次数:10 匹配数字:你好 WORLD2.0 替换次数:1 匹配非数字:hihihihihihihihihihi2 替换次数:10 匹配任意字符:hihihihihihihihihihihi 替换次数:11 输出完成 (耗时 0 秒) - 正常终止
例子:
实现电话号码的匹配
#!/usr/bin/env python # -*- coding=utf-8 -*- #Using GPL v2.7 #Author: leexide@126.com # 特殊字符的使用 import re # 限定符的使用 tel1 = "0791-1234567" print re.findall(r"\d{3}-\d{8}|\d{4}-\d{7}", tel1) tel2 = "010-12345678" print re.findall(r"\d{3}-\d{8}|\d{4}-\d{7}", tel2) tel3 = "(010)12345678" print re.findall(r"[\(]?\d{3}[\)-]?\d{8}|[\(]?\d{4}[\)-]?\d{7}", tel3) print re.findall(r"a.*?c", "abcabc")
输出结果:
---------- python2.7 ---------- ['0791-1234567'] ['010-12345678'] ['(010)12345678'] ['abc', 'abc'] 输出完成 (耗时 0 秒) - 正常终止
正则表达式的解析十分费时,如果多次使用findall()的方式匹配字符串,搜索效率可能比较低。如果要多次使用同一规则匹配字符串,可以使用compile()函数进行预编译,compile函数返回1个pattern对象。该对象拥有一系列方法用于查找、替换或扩展字符串,从而提高字符串的匹配速度。
pattern对象的属性和方法。
例子:
在1个字符串中查找多个数字,使用compile()函数以提高查找的效率。
#!/usr/bin/env python # -*- coding=utf-8 -*- #Using GPL v2.7 #Author: leexide@126.com # 特殊字符的使用 import re # compile()预编译 s = "1abc23def45" p = re.compile(r"\d+") print p.findall(s) print p.pattern
输出结果:
---------- python2.7 ---------- ['1', '23', '45'] \d+ 输出完成 (耗时 0 秒) - 正常终止
函数compile()通常与match()、search()、group()一起使用,对含有分组的正则表达式进行解析。正则表达式的分组从左往右开始计数,第1个出现的圆括号标记为第1组,依次类推。此外还有0号组,0号组用于存储匹配整个正则表达式的结果。match()和search()将返回1个match对象,match对象提供了一系列的方法和属性来管理匹配的结果。
match对象的方法和属性
例子:
#!/usr/bin/env python # -*- coding=utf-8 -*- #Using GPL v3.3 #Author: leexide@126.com import re p = re.compile(r"(abc)\1") m = p.match("abcabcabc") print m.group(0) print m.group(1) print m.group() p = re.compile(r"(?P<one>abc)(?P=one)") m = p.search("abcabcabc") print m.group(0) print m.group("one") print m.groupdict().keys() print m.groupdict().values()
输出结果:
---------- python2.7 ---------- abcabc abc abcabc abcabc abc ['one'] ['abc'] 输出完成 (耗时 0 秒) - 正常终止