《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()