正则表达式
findall方法, 查找字符串中匹配的所有子串, 返回列表, 如果没有匹配到, 返回空列表
import re
s = 'hello world'
print(re.findall('l', s))
match方法, 从字符串起始位置开始匹配到的第一个子串, 返回匹配对象, 如果没有匹配到, 返回None
print(re.match('o', s))
print(re.match('hello', s).group())
search方法, 查找字符串中匹配的第一个子串, 返回匹配对象, 如果没有匹配到, 返回None
注意: match方法只从字符串的起始位置开始匹配, search方法匹配整个字符串
print(re.search('l', s))
print(re.search('l', s).group())
sub方法, 替换字符串中匹配的所有子串, 返回替换后的字符串
print(re.sub('l', 'x', s))
单字符匹配, .表示任意字符, *表示0个或多个字符, +表示1个或多个字符, ?表示0个或1个字符, (ab)表示匹配ab, 匹配成功返回True, 否则返回False
[abc]表示匹配a或b或c, [^abc]表示匹配非a或b或c, ^表示匹配非字符, $表示匹配字符串结束位置, |表示或, (a|b)表示匹配a或b
\d表示匹配数字, \D表示匹配非数字, \w表示匹配字母数字下划线汉字(不包括标点符号), \W表示匹配非字母数字下划线, \s表示匹配空格, \S表示匹配非空格
{n}表示匹配n个字符, {n,m}表示匹配n到m个字符, {n,}表示匹配n个或多个字符(尽可能的多), {,m}表示匹配0到m个字符(尽可能的多)
print(re.findall('.', s))
print(re.findall('..', s))
print(re.findall('.?', s))
print(re.findall('.+', s))
print(re.findall('.+?', s))
print(re.findall('\d', '123abc'))
print(re.findall('\d\d', '123abc'))
print(re.findall('\D', '123abc'))
print(re.findall('\D\D', '123abc'))
print(re.findall('\w', '123abc'))
print(re.findall('\W', s))
print(re.findall('\s', s))
print(re.findall('\S', s))
print(re.findall('\S\s', s))
print(re.findall('.{3}', s))
print(re.findall('.{3,5}', s))
print(re.findall('.{3,}', s))
print(re.findall('.{,5}', s))
print(re.findall('.{1,5}', s))
print(re.findall('[abc]', '123abc'))
print(re.findall('[^abc]', '123abc'))
print(re.findall('world$', s))
print(re.findall('h|e', s))
print(re.findall('h|e|l|o', s))
url = '<img class="image_X-V-y" src="http://gips3.baidu.com/it/u=1821127123,1149655687&fm=3028&app=3028&f=JPEG&fmt=auto?w=720&h=1280" alt="">'
print(re.findall('src="(.*?)"', url))
用正则表达式规范用户名和密码
用户名8-12位, 字母开头, 不能有中文
密码不能和用户名相同, 至少8位, 不能超过16位
try:
username = input('请输入用户名: ')
if len(re.match('[A-Za-z]+[A-Za-z0-9]{7,11}$', username).group()) > 0:
print('用户名格式正确')
password = input('请输入密码: ')
if username == password:
raise Exception('密码不能和用户名相同')
if len(re.match('[a-zA-Z0-9]{7,15}', password).group()) > 0:
print('密码格式正确')
except AttributeError as e:
print('用户名或密码格式错误,', e)
except Exception as e:
print(e)