编程语言
首页 > 编程语言> > Python编程快速上手:模式匹配与正则表达式

Python编程快速上手:模式匹配与正则表达式

作者:互联网

 1 def isPhoneNumber(text):
 2   if len(text) != 12:
 3     return False
 4   for i in range(0, 3):
 5     if not text[i].isdecimal():
 6       return False
 7   if text[3] != '-':
 8     return False
 9   for i in range(4, 7):
10     if not text[i].isdecimal():
11       return False
12   if text[7] != '-':
13     return False
14   for i in range(8, 12):
15     if not text[i].isdecimal():
16       return False
17   return True
18 
19 message = 'Call me at 415-555-1011 tomorrow.415-555-9999 is my office.'
20 for i in range(len(message)):
21   chunk = message[i:i+12]
22   if isPhoneNumber(chunk):
23     print('Phone number fround: ' + chunk)
24 print('Done')
1 C:\PyProjects>C:/Python37/python3.exe c:/PyProjects/isPhoneNumber.py
2 Phone number fround: 415-555-1011
3 Phone number fround: 415-555-9999
4 Done
运行结果

 

 1 #!/usr/bin/env python
 2 #-*- encoding:utf-8 -*-
 3 import re
 4 def isPhoneNumber(text):
 5   if len(text) != 12:
 6     return False
 7   for i in range(0, 3):
 8     if not text[i].isdecimal():
 9       return False
10   if text[3] != '-':
11     return False
12   for i in range(4, 7):
13     if not text[i].isdecimal():
14       return False
15   if text[7] != '-':
16     return False
17   for i in range(8, 12):
18     if not text[i].isdecimal():
19       return False
20   return True
21 
22 phoneNumRegex = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d')
23 mo = phoneNumRegex.search('My number is 415-555-4242.')
24 print('Phone number found: ' + mo.group())
1 C:\PyProjects>C:/Python37/python3.exe c:/PyProjects/isPhoneNumber.py
2 Phone number found: 415-555-4242
运行结果

Python中使用正则表达式的步骤

  1. 用import re导入正则表达式模块
  2. 用re.compile()函数创建一个Regex对象(使用原始字符串)
  3. 向Regex对象的search()方法传入想查找的字符串,它返回一个Match对象。
  4. 调用Match对象的group()方法,返回实际匹配文本的字符串。

 

标签:12,False,Python,text,正则表达式,range,return,isdecimal,模式匹配
来源: https://www.cnblogs.com/helon/p/16184105.html