python核心编程课后习题-正则式1

来源:互联网 发布:cocos2d.js sdk 编辑:程序博客网 时间:2024/05/17 06:07

1-1 识别后续字符串:"bat"、"bit"、"but"、"hat"、或者"hut"

import re

string="but"
patt = "bat|bit|but|hat|hit|hut"
m=re.match(patt,string)
print (m.group())

 

 

1-2 匹配由单个空格分隔的任意单词对,也就是姓和名

string="Tom Cruise"patt = "[a-zA-Z]+\s[a-zA-Z]+"m=re.match(patt,string)print (m.group())

 

 

1-3匹配由单个逗号和单个空白符分隔的任何单词和单个首字符,如姓氏的首字母。

string="Tom Cruise, tom"patt = "[a-zA-Z]+,\s[a-zA-Z]+"m=re.search(patt,string)print (m.group())

 

 

1-4 匹配所有有效python标识符的集合

string="_ssdf_12f_sdf"#以下划线或字母开头的集合patt = '[A-Za-z_]+[_\w]+'m=re.match(patt,string)print (m.group())

1-5 根据读者当地格式,匹配街道地址(使你的正则表达式足够通用,来匹配任意数量的街道单词,包括类型名称)。例如,美国街道地址使用如下格式:1180 Brodeaux Drive。使你的正则表达式足够灵活,以支持多单词的街道名称,如3120 De la Cruz Boulevard

string="3120 De la Cruz Boulevard "patt = '\d+(\s[a-zA-Z]+)+'m=re.match(patt,string)print (m.group())

 

1-6 匹配以“www”起始且以“.com”结尾的简单web域名;例如,www://yahoo.com。选做题:你的正则表达式也可以支持其他高级域名,如.edu、.net等(例如,http://www.foothill.edu)

string="http://www.foothill.edu"patt = '(www\.)\w+\.(com|edu|net)'m=re.search(patt,string)print (m.group())

 

1-7匹配所有能够表示python整数

string="+1191800"patt = '[+-]?\d+$'m=re.match(patt,string)print (m.group())

 

1-8匹配所有能够表示python长整数的字符串集

string="1191800L"patt = '[+-]?\d+[lL]'m=re.match(patt,string)print (m.group())

1-9 匹配所有能够表示python浮点数的字符串集

string="1191800.0"patt = '[+-]?\d+\.\d+'m=re.match(patt,string)print (m.group())

 

1-10匹配所有能够表示python复数的字符串集

string="10+10j"patt = '[+-]?\d+[+-]\d+j$'m=re.match(patt,string)print (m.group())

 

1-11 匹配所有能够表示有效电子邮件地址的集合(从一个宽松的正则表达式开始,然后尝试使他尽可能严谨,不过要保持正确的功能)

string="qweq-#$@wer1231(.com"patt = '[\w\W]+@[\w\W]+'m=re.match(patt,string)print (m.group())

 

1-12 匹配所有能够表示有效地网站地址的集合(URL)(从一个宽松的正则表达式开始完后尝试使它尽可能严谨,不过要保持正确功能)。

string="http://sdfwew.com http://sdfsdfs_sdf.com.cn"regex=re.compile("(http://([\w.]+)*)")print(regex.findall(string))

 

1-13 type()。内置函数type()返回一个类型对象,能够从字符串中提取实际类型名称。

stype = str(type(3))print (stype)regex=re.compile("\'([\w]+)\'")print(regex.findall(stype))

 

1-14 处理日期。1.2节提供了来匹配单个或者两个数字字符串的正则表达式模式,来表示1-9的月份(0?[1-9]),创建个正则式来表示标准日历中剩余的三个月的数字。

string="01 1 2 11 12 10"regex=re.compile("([1|0]?[0-9])")print(regex.findall(string))

 

1-15 处理信用卡号码。编写一些代码,这些代码不但能够识别具有正确格式的号码,而且能够识别有效地信用卡号码。

string  ="1234-567890-12345"string2 ="1234-5678-9012-3456"patt = '\d{4}-\d{4}(\d{2})?-\d{4}((\d)|(-\d{4})){1}'m=re.match(patt,string)print(m.group())

原创粉丝点击