正则表达式练习题2
? 1、匹配一行文字中的所有开头的字母内容 #coding=utf-8 ? import re s="i love you not because of who you are,but because of who i am when i am with you" content=re.findall(r"bw",s) print content c:Python27Scripts>python task_test.py [‘i‘,‘l‘,‘y‘,‘n‘,‘b‘,‘o‘,‘w‘,‘a‘,‘i‘,‘y‘] ? 2、匹配一行文字中的所有开头的数字内容 s="i love you not because 12sd 34er 56df e4 54434" content=re.findall(r"bd",sans-serif; background-color: #faf7ef;">c:Python27Scripts>python task_test.py [‘1‘,‘3‘,‘5‘,‘5‘] 3、匹配一行文字中的所有开头的数字内容或数字内容 >>> print re.match(r"w+","123sdf").group() 123sdf 4、 只匹配包含字母和数字的行 s="i love you not becausen12sd 34er 56ndf e4 54434" content=re.findall(r"w+",s,re.M) 5、写一个正则表达式,使其能同时识别下面所有的字符串:‘bat‘,‘bit‘,‘but‘,‘hat‘,‘hit‘,‘hut‘ s="‘bat‘,‘hut" content=re.findall(r"..t",sans-serif; background-color: #faf7ef;">[‘bat‘,‘hut‘] 6、匹配所有合法的python标识符 s="awoeur awier [email?protected]# @#4_-asdf3$^&()+?><dfg$n$" content=re.findall(r".*",re.DOTALL) print s awoeur awier [email?protected]# @#4_-asdf3$^&()+?><dfg$ $ [‘awoeur awier [email?protected]# @#4_-asdf3$^&()+?><dfg$n$‘,‘‘] 7、提取每行中完整的年月日和时间字段 s="""se234 1987-02-09 07:30:00 ??? 1987-02-10 07:25:00""" content=re.findall(r"d{4}-d{2}-d{2} d{2}:d{2}:d{2}",sans-serif; background-color: #faf7ef;">se234 1987-02-09 07:30:00 ??? 1987-02-10 07:25:00 [‘1987-02-09 07:30:00‘,‘1987-02-10 07:25:00‘] 8、将每行中的电子邮件地址替换为你自己的电子邮件地址 s="""[email?protected],[email?protected],[email?protected] ??? [email?protected],[email?protected] ??? [email?protected]""" content=re.sub(r"[email?protected]w+.com","[email?protected]",sans-serif; background-color: #faf7ef;">print "_______________________________________" [email?protected],[email?protected],[email?protected] ??? [email?protected],[email?protected] ??? [email?protected] _______________________________________ [email?protected],[email?protected],[email?protected] ??? [email?protected],[email?protected] ??? [email?protected] 9、匹配home关键字: >>> re.findall(r"home","skjdfoijower home?? homewer") [‘home‘,‘home‘] 1、使用正则提取出字符串中的单词 s="""i love you not because of who 234 you are,234 but 3234ser because of who i am when i am with you""" content=re.findall(r"b[a-zA-Z]+b",‘of‘,‘who‘,‘are‘,‘am‘,‘when‘,‘with‘,‘you‘] 2、使用正则表达式匹配合法的邮件地址: s="""[email?protected],[email?protected] [email?protected] [email?protected] [email?protected] saldkfj.com [email?protected]""" content=re.findall(r"[email?protected]w+.com",sans-serif; background-color: #faf7ef;">[‘[email?protected]‘,‘[email?protected]‘,‘[email?protected]‘,‘[email?protected]‘] (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |