1. 程式人生 > >5.2.3 案例精選

5.2.3 案例精選

正則 hone 文件中 col import ESS index body -s

  例 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 目標文件名”查找並輸出目標文件中的標識符。

5.2.3 案例精選