《python 核心编程》第15章正则表达式 答案
看了两天正则表达式,总算是看完了也算入门了吧,顺便把python 15章的习题也给一并清了。 以下是个人的答案,若有不当之处请指教 #coding=utf-8 #!/bin/env python import re #1. 识别下列字符串:“bat,” “bit,” “but,” “hat,” “hit,” 或 “hut” def test1(): bt='bat|bit|but|hat|hit|hut' inputstr=raw_input('input needs to match String') m=re.match(bt,inputstr) if m is not None:print(m.group()) else:print 'not match' # test1() #2.匹配用一个空格分隔的任意一对单词,比如,名和姓 def test2(): bt='(.*)\s(.*)' inputstr=raw_input('输入您的姓名,姓与名之间用空格隔开\n') m=re.match(bt,inputstr) if m is not None: print('您的姓是:%s'%m.group(1)) print('您的名是:%s'%m.group(2)) print('all is:%s'%m.group(0)) else:print 'not match' #