这里我们将使用到re模块,Python通过re模块提供对正则表达式的支持。使用re的一般步骤是先将正则表达式的字符串形式编译为Pattern实例,然后使用Pattern实例处理文本并获得匹配结果(一个Match实例),最后使用Match实例获得信息,进行其他的操作,大致步骤如下:
#!/usr/bin/env python
#-*- coding: utf-8 -*-
import re
pattern = re.compile('[0-9]+')
match = pattern.findall('12345')
if match:
***************
else:
***************
re.compile(strPattern[, flag]):
这个方法是Pattern类的工厂方法,用于将字符串形式的正则表达式编译为Pattern对象。 第二个参数flag是匹配模式,取值可以使用按位或运算符’|’表示同时生效,比如re.I | re.M。另外,你也可以在regex字符串中指定模式,比如re.compile(‘pattern’, re.I | re.M)与re.compile(‘(?im)pattern’)是等价的。
可选值有:
re.I(re.IGNORECASE): 忽略大小写(括号内是完整写法,下同)
M(MULTILINE): 多行模式,改变'^'和'$'的行为(参见上图)
S(DOTALL): 点任意匹配模式,改变'.'的行为
L(LOCALE): 使预定字符类 \w \W \b \B \s \S 取决于当前区域设定
U(UNICODE): 使预定字符类 \w \W \b \B \s \S \d \D 取决于unicode定义的字符属性
X(VERBOSE): 详细模式。这个模式下正则表达式可以是多行,忽略空白字符,并可以加入注释。
findall(string[, pos[, endpos]]) | re.findall(pattern, string[, flags]):
搜索string,以列表形式返回全部能匹配的子串。
2.下面是我截取一个代码片段:
def password_check_contain_upper(self, password):
pattern = re.compile('[A-Z]+')
match = pattern.findall(password)
if match:
return True
else:
return False
def password_check_contain_num(self,password):
pattern = re.compile('[0-9]+')
match = pattern.findall(password)
if match:
return True
else:
return False
def password_check_contain_zh_cn(self,password):
for ch in password.decode('utf-8'):
if u'\u4e00' <= ch <= u'\u9fff':
return True
else:
return False
def password_check_contain_lower(self, password):
pattern = re.compile('[a-z]+')
match = pattern.findall(password)
if match:
return True
else:
return False