正则的几道练习

来源:互联网 发布:淘宝店铺内部人员解封 编辑:程序博客网 时间:2024/06/08 00:46
#1.匹配一段文本中的每行的邮箱
y =r'123@qq.comaaa@163.combbb@126.comasdfasfs33333@adfcom'
# 2.匹配一段文本中的每行的时间字符串,比如:‘1990-07-12’;
分别打印出年,月,日


Time =r'asfasf1990-07-12asdfAAA1992-12-10-34241'


#3、 匹配一段文本中所有的身份证数字。
a='sfafsf,34234234234,1231313132,154785625475896587,sdefgr54184785ds85,4864465asf86845'


# 4、 匹配qq号。(腾讯QQ号从10000开始)
q='3344,88888,7778957,10000,99999,414,4,867287672999999999999'




#5 匹配浮点数
value = '5.888-21-2.899-2,1'


#7 匹配出所有的整数

a='1,-3,a,-2.5,7.7,asdf'

以下是答案:

import rey =r'123@qq.comaaa@163.combbb@126.comasdfasfs33333@adfcom'pattern = re.compile(r'\w+@(?:qq|163|126).com')result = re.findall(pattern,y)print(result)value = 'addfsdf1990-07-12sfs'pattern1 = re.compile(r'\d{4}-\d{2}-\d{2}')pattern2 = re.compile(r'(\d{4})-(\d{2})-(\d{2})')result1 = re.findall(pattern1,value)result2 = re.findall(pattern2,value)print(result1)print(result2[0][0],result2[0][1],result2[0][2])a='sfafsf,34234234234,1231313132,154785625475896587,sdefgr54184785ds85,4864465asf86845'pattern3 = re.compile(r'\d{18}')result3 = re.findall(pattern3,a)print(result3)q='3344,88888,7778957,10000,99999,414,4,867287672999999999999'pattern4 = re.compile(r'[1-9][0-9]{4,}')result4 = re.findall(pattern4,q)print(result4)value1 = '5.888-21-2.899-2,1'pattern5 = re.compile(r'-?\d+\.?\d*')result5 = re.findall(pattern5,value1)print(result5)a1='1,-3,a,-2.5,7.7,asdf'  #先把单个字符分开,整数的字符是'1'或'-3'数字后面直接跟'a2 = str(re.split(',',a1))#那么pattern就可以写成r"'-?\d+'"pattern6 = re.compile(r"'(-?\d)'")result6 = re.findall(pattern6,a2)print(result6)
re.findall得到的一个列表,然后每一项中不过不带()或者(?<name>)那么就是一个单个组成的列表

否则就是得到一个tuple组成的列表。

原创粉丝点击