Python编程快速上手:模式匹配与正则表达式
2022/4/24 1:12:50
本文主要是介绍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')
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
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())
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 C:\PyProjects>C:/Python37/python3.exe c:/PyProjects/isPhoneNumber.py 2 Phone number found: 415-555-4242运行结果
Python中使用正则表达式的步骤
- 用import re导入正则表达式模块
- 用re.compile()函数创建一个Regex对象(使用原始字符串)
- 向Regex对象的search()方法传入想查找的字符串,它返回一个Match对象。
- 调用Match对象的group()方法,返回实际匹配文本的字符串。
这篇关于Python编程快速上手:模式匹配与正则表达式的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-08有遇到过吗?同样的规则 Excel 中 比Python 结果大
- 2024-03-30开始python成长之路
- 2024-03-29python optparse
- 2024-03-29python map 函数
- 2024-03-20invalid format specifier python
- 2024-03-18pool.map python
- 2024-03-18threads in python
- 2024-03-14python Ai 应用开发基础训练,字符串,字典,文件
- 2024-03-13id3 algorithm python
- 2024-03-13sum array elements python