python Re 模块
Python 的 re 模块(Regular Expression 正则表达式)提供各种正则表达式的匹配操作,在文本解析、复杂字符串分析和信息提取时是一个非常有用的工具,下面我主要总结了re的常用方法。
密码复杂度匹配(密码中必须包含大小写字母、数字、特称字符,至少8个字符,最多30个字符。):
regex_password = "(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z0-9]).{8,30}"
p = re.compile(regex_password)
print(p.match("12!@#$%^&A"))
re的简介
使用python的re模块,尽管不能满足所有复杂的匹配情况,但足够在绝大多数情况下能够有效地实现对复杂字符串的分析并提取出相关信息。python 会将正则表达式转化为字节码,利用 C 语言的匹配引擎进行深度优先的匹配。
- import re
- print re.__doc__
可以查询re模块的功能信息,下面会结合几个例子说明。
re的正则表达式语法
| 语法 | 意义 | 说明 |
| "." | 任意字符 | |
| "^" | 字符串开始 | '^hello'匹配'helloworld'而不匹配'aaaahellobbb' |
| "$" | 字符串结尾 | 与上同理 |
| "*" | 0 个或多个前面出现的正则表达式(贪婪匹配) | [A-Za-z0-9]* 注意:使用search必须从字符串最开始匹配 |
| "+" | 1 个或多个前面出现的正则表达式(懒惰匹配) | [a-z]+\.com |
| "?" | 0 个或1个前面出现的正则表达式(贪婪匹配) | goo? 注意:使用search必须从字符串最开始匹配 |
| {N} | 匹配N次前面出现的正则表达式 | a{6}匹配6个a |
| {M,N} | 匹配M~N次前面出现的正则表达式 | [0-9]{15,18}匹配15-18位的身份证 |
| [...] | 匹配来自字符集的任意单一字符 | [0-9]、[a-z]、[A-Z]、[^0]、[aeiou] |
| "|" | 或 | A|B,或运算 |
| (...) | 匹配括号中任意表达式 | ([0-9]{3})?,f(oo|u)bar |
| (?#...) | 注释,可忽略 |
|
| (?=...) | Matches if ... matches next, but doesn't consume the string. | '(?=test)' 在hellotest中匹配hello |
| (?!...) | Matches if ... doesn't match next. | '(?!=test)' 若hello后面不为test,匹配hello |
| (?<=...) | Matches if preceded by ... (must be fixed length). | '(?<=hello)test' 在hellotest中匹配test |
| (?<!...) | Matches if not preceded by ... (must be fixed length). | '(?<!hello)test' 在hellotest中不匹配test |
正则表达式特殊序列表如下:
| 特殊序列符号 | 意义 |
| \A \Z | \A 等于^ \Z 等于 $ |
| \b | 匹配位于开始或结尾的空字符串 \B与之相反 |
| \d | 匹配任何十进制,相当于[0-9] (\D与\d相反,\D不匹配任何非数值型的数字) |
| \s | 匹配任意空白字符:[\t\n\r\r\v] \S与之相反 |
| \w | 匹配任意数字和字母和下划线:[a-zA-Z0-9_] \W与之相反 |
re的主要功能函数
常用的功能函数包括:compile、search、match、split、findall(finditer)、sub(subn)
compile
re.compile(pattern[, flags])
编译正则表达式(推荐,可以加快re执行的速度),返回RegexObject对象,然后可以通过RegexObject对象调用match()和search()方法。
prog = re.compile(pattern)
result = prog.match(string)
跟result = re.match(pattern, string)是等价的。
第一种方式能实现正则表达式的重用。
search
re.search(pattern, string[, flags])
search (string[, pos[, endpos]])
作用:在字符串中查找匹配正则表达式模式的位置,返回 MatchObject 的实例,如果没有找到匹配的位置,则返回 None。
match
re.match(pattern, string[, flags])
match(string[, pos[, endpos]])
作用:match() 函数只在字符串的开始位置尝试匹配正则表达式,也就是只报告从位置 0 开始的匹配情况,而 search() 函数是扫描整个字符串来查找匹配。如果想要搜索整个字符串来寻找匹配,应当用 search()。
下面是几个例子:
例:最基本的用法,通过re.RegexObject对象调用
import re
a = 'ab_c@qq.cn'
b = re.compile('^[A-Za-z][\w]{5,17}\@\w+\.(com|cn)') # 匹配邮件地址,可使用字母、数字、下划线,需以字母开头,长度6~18个字符
m = b.match(a)
print(m.group())
说明一下:r是raw(原始)的意思。因为在表示字符串中有一些转义符,如表示回车'\n'。如果要表示\表需要写为'\\'。但如果我就是需要表示一个'\'+'n',不用r方式要写为:'\\n'。但使用r方式则为r'\n'这样清晰多了。
例:设置flag
#r2 = re.compile(r'n$', re.S)
#r2 = re.compile('\n$', re.S)
r2 = re.compile('World$', re.I)
if r2.search('helloworld\n'):
print 'search succeeds'
else:
print 'search fails'
split
re.split(pattern, string[, maxsplit=0, flags=0])
split(string[, maxsplit=0])
作用:可以将字符串匹配正则表达式的部分割开并返回一个列表
例:简单分析ip
- #!/usr/bin/env python
- import re
- r1 = re.compile('\W+')
- print r1.split('192.168.1.1')
- print re.split('(\W+)','192.168.1.1',1)
结果如下:
['192', '168', '1', '1']
['192', '168.1.1']
findall
re.findall(pattern, string[, flags])
import re aa = "/Users/shongbing/Pyphere/vmware/bin/python3/Users/shongbing/PycharmProjects/Pyphere/020 'get_performance' for host.py" res = re.findall("020 '(.*)'", aa) print(res) >>> ['get_performance']
作用:在字符串中找到正则表达式所匹配的所有子串,并组成一个列表返回
例:查找[]包括的内容(贪婪和非贪婪查找)
import re
print(re.findall('\D+','12a34b56c78d90'))
>>>['a', 'b', 'c', 'd']
import re
print(re.findall('\d+','12a34b56c78d90'))
>>>['12', '34', '56', '78', '90']
finditer
re.finditer(pattern, string[, flags])
finditer(string[, pos[, endpos]])
说明:和 findall 类似,在字符串中找到正则表达式所匹配的所有子串,并组成一个迭代器返回。
import re
print(re.finditer('\d+','12a34b56c78d90'))
>>><callable_iterator object at 0x009BE5D0>
sub
re.sub(pattern, repl, string[, count, flags])
sub(repl, string[, count=0])
说明:在字符串 string 中找到匹配正则表达式 pattern 的所有子串,用另一个字符串 repl 进行替换。如果没有找到匹配 pattern 的串,则返回未被修改的 string。Repl 既可以是字符串也可以是一个函数。
例:
- #!/usr/bin/env python
- import re
- p = re.compile('(one|two|three)')
- print p.sub('num','one word two words three words apple', 2)
?P<name>分组匹配
>>> res = re.search("(?P<province>[0-9]{4})(?P<city>[0-9]{2})(?P<birthday>[0-9]{4})","371481199306143242")>>> res.groupdict()
{'birthday': '1993', 'province': '3714', 'city': '81'}
>>> res.group("province")
'3714'
>>> res.group("city")
'81'
>>> res.group("birthday")
'1993'

浙公网安备 33010602011771号