Python核心编程正则表达式练习题1-1 识别后续的字符串:“bat”、“bit”、“but”、“hat”、“hit”或者“hut”

# 1-1 识别后续的字符串:“bat”“bit”“but”“hat”“hit”或者“hut”

 1 import re
 2 
 3 # 正则表达式,|元字符表示选择“或”
 4 # character = 'bat|bit|but|hat|hit|hut' # 方法一
 5 # character = '[bh][aiu]t'  # 方法二
 6 character = '(b|h)(a|i|u)t' # 方法三
 7 
 8 # 测试数据
 9 data = 'bat'
10 data1 = 'bit'
11 data2 = 'but'
12 data3 = 'hat'
13 data4 = 'hit'
14 data5 = 'hut'
15 
16 # 测试开始
17 m = re.match(character, data)
18 m1 = re.match(character, data1)
19 m2 = re.match(character, data2)
20 m3 = re.match(character, data3)
21 m4 = re.match(character, data4)
22 m5 = re.match(character, data5)
23 
24 
25 if m is not None:
26     print("data与character匹配成功,结果为:")
27     print(m.group())
28 
29 if m1 is not None:
30     print("data1与character匹配成功,结果为:")
31     print(m1.group())
32 
33 if m2 is not None:
34     print("data2与character匹配成功,结果为:")
35     print(m2.group())
36 
37 if m3 is not None:
38     print("data3与character匹配成功,结果为:")
39     print(m3.group())
40 
41 if m4 is not None:
42     print("data4与character匹配成功,结果为:")
43     print(m4.group())
44 
45 if m5 is not None:
46     print("data5与character匹配成功,结果为:")
47     print(m5.group())

"""
/usr/bin/python3.5 /studydisk/other/正则表达式/demo1.py
datacharacter匹配成功,结果为:
bat
data1character匹配成功,结果为:
bit
data2character匹配成功,结果为:
but
data3character匹配成功,结果为:
hat
data4character匹配成功,结果为:
hit
data5character匹配成功,结果为:
hut

&&
/usr/bin/python3.5 /studydisk/other/正则表达式/demo1.py
datacharacter匹配成功,结果为:
bat
data1character匹配成功,结果为:
bit
data2character匹配成功,结果为:
but
data3character匹配成功,结果为:
hat
data4character匹配成功,结果为:
hit
data5character匹配成功,结果为:
hut

&&
datacharacter匹配成功,结果为:
bat
data1character匹配成功,结果为:
bit
data2character匹配成功,结果为:
but
data3character匹配成功,结果为:
hat
data4character匹配成功,结果为:
hit
data5character匹配成功,结果为:
hut

"""



posted @ 2019-08-16 16:56  Ranxf  阅读(958)  评论(0编辑  收藏  举报