5.2.3 案例精选
例 1 :使用正则表达式提取字符串中的电话号码。
1 import re
2
3 telNumber = '''Suppose my Phone No. is 0535-1234567,yours is 010-12345678,his is 025-87654321.'''
4 pattern = re.compile(r'(\d{3,4})-(\d{7,8})')
5
6 index = 0
7 while True:
8 matchResult = pattern.search(telNumber,index) #从指定位置开始匹配
9 if not matchResult:
10 break
11 print('-' * 30)
12 print('Success:')
13 for i in range(3):
14 print('Sarched content:',matchResult.group(i),'Start from:',matchResult.start(i),'End at:',
matchResult.end(i),'Its span is:',matchResult.span(i))
15 index = matchResult.end(2) #指定下次匹配的开始位置
16
17 '''
18 ------------------------------
19 Success:
20 Sarched content: 0535-1234567 Start from: 24 End at: 36 Its span is: (24, 36)
21 Sarched content: 0535 Start from: 24 End at: 28 Its span is: (24, 28)
22 Sarched content: 1234567 Start from: 29 End at: 36 Its span is: (29, 36)
23 ------------------------------
24 Success:
25 Sarched content: 010-12345678 Start from: 46 End at: 58 Its span is: (46, 58)
26 Sarched content: 010 Start from: 46 End at: 49 Its span is: (46, 49)
27 Sarched content: 12345678 Start from: 50 End at: 58 Its span is: (50, 58)
28 ------------------------------
29 Success:
30 Sarched content: 025-87654321 Start from: 66 End at: 78 Its span is: (66, 78)
31 Sarched content: 025 Start from: 66 End at: 69 Its span is: (66, 69)
32 Sarched content: 87654321 Start from: 70 End at: 78 Its span is: (70, 78)
33 '''
例 2:使用正则表达式提取Python程序中的类名、函数名已经变量名等标识符。
将下面的代码保存为FindIdentifiersFromPyFile.py,在名利提示符环境中使用命令“Python FindIdentifiersFromPyFile.py 目标文件名”查找并输出目标文件中的标识符。