《Python unix与linux系统管理指南》学习笔记
Python中使用正则表达式,应该要养成创建编译后的正则表达式的习惯,使用方法如下:
- #!/usr/bin/env python
- import re
- def run_re():
- pattern = 'ERROR'
- re_obj = re.compile(pattern)
- infile = open('/home/udb/jt.txt', 'r')
- match_count = 0
- lines = 0
- for line in infile:
- match = re_obj.search(line)
- if match:
- match_count += 1
- lines += 1
- return (lines, match_count)
- if __name__ == "__main__":
- lines, match_count = run_re()
- print 'LINES--->', lines
- print 'MATCHES--->', match_count
常用的正则表达式方法有findall(), finditer(), match(), search()
本文介绍如何在Python中利用正则表达式进行文本匹配与搜索。通过具体示例展示了正则表达式的编译及使用方法,包括findall(), finditer(), match(), search()等常用函数的应用。
1734

被折叠的 条评论
为什么被折叠?



