Python全栈工程师

25.1-正则表达式习题讲解

2019-10-20  本文已影响0人  BeautifulSoulpy

只有自己成为自己的贵人,别人才会成为你的贵人!

正则表达式一旦会用,后面都不是问题;
不一定支持断言(未必所有方言都支持),别再里面加断言;
但它支持分组,在替换的时候要引用前面分组,这个时候就要使用分组;

总结:
1.匹配先左后右; 注意贪婪与非贪婪的模式;
2.反复匹配、搜索用 set;

练习1:匹配邮箱地址;

test@hot-mail.com
v-ip@magedu.com
web.manager@magedu.com.cn
super.user@google.com
a@w-a-com

#练习1:匹配邮箱地址;
import re

s = '''
test@hot-mail.com
v-ip@magedu.com
web.manager@magedu.com.cn
super.user@google.com
a@w-a-com'''

#.*@.*\.com\.|(\w+)$

regex = re.compile('.*@.*\..*')
regex = re.compile('[\w-.]+@[\w-.]+\.\w+')   # 提取邮箱()
print(regex.findall(s))
#----------------------------------------
['test@hot-mail.com', 'v-ip@magedu.com', 'web.manager@magedu.com.cn', 'super.user@google.com']

练习2: 匹配html 标记内的内容;

h = "<a href='http://www.magedu.com/index.html' target='_blank'>马哥教育</a>"

# 练习2: 匹配html 标记内的内容;
h = "<a href='http://www.magedu.com/index.html' target='_blank'>马哥教育</a>"

regex = re.compile('>\w+')
regex = re.compile('>(.*)<')    # a 标记的内容;
lst = regex.findall(h)
print(regex.findall(h))
#------------------------------------------
['马哥教育']


总结:
1. **a标记中标题的提取:      >(.*)</a>**
      复杂标记的提取   (<a[^<>]*>)(.*)</a>
练习3: 匹配合法的URL;
u = '''http://www.magedu.com/index.html
https://login.magedu.com
file:///ect/sysconfig/networkk'''

regex = re.compile('[https]{2,5}:[//www]{2,5}.*(?<=.)[html|com]')
regex = re.compile('(?<scheme>\w+)://(.*)')
print(regex.findall(u))
#----------------------------------------------
['http://www.magedu.com/index.html', 'https://login.magedu.com']

总结:
(?<scheme>\w+)://(?<path>.*)/(?<file>.*)    # URL匹配各个成分
练习4:匹配二代身份证 ID ;

17位数字+1位校验码组
前6位地址码,8位出生

c = '''321105700101003
321105197001010030
11210020170101054X'''

regex = re.compile('\d{6}[1-2]\d{3}[0-1]\d[0-3]\d{4}[X|\d]')
print(regex.findall(c))
#-------------------------------------
['321105197001010030', '11210020170101054X']

总结:
1. 写|的时候,谁前谁后还是有关系的;   \d{17}[\dxX]|\d{15}
练习5:判断密码强弱

要求密码必须由 10-15位 指定字符组成:
十进制数字
大写字母
小写字母
下划线
要求四种类型的字符都要出现才算合法的强密码
例如:Aatb32_67mnq,其中包含大写字母、小写字母、数字和下划线,是合格的强密码


总结:
1. 排序的方案:先排序,再匹配;  \d+[A-Z]+_[a-z+]   
2. 试4次,遍历4次;非法字符;
    先判断位数
3. 给密码类型打分;

练习6:单词 统计 word count

对sample文件进行单词统计,要求使用正则表达式

思路1:对  字符、-   取反  后是非-字符分割split;
regex = re.compile('[^\w-]+')    #

上一篇下一篇

猜你喜欢

热点阅读