ITeye博客

Python中使用正则表达式

flynewton · 2011-01-30 14:02 · Python相关 · 编程语言 · Markdown

关键字: python , 正则表达式

《Python unix与linux系统管理指南》学习笔记

Python中使用正则表达式,应该要养成创建编译后的正则表达式的习惯,使用方法如下:

源码打印?

  1. #!/usr/bin/env python
  2. import re
  3. def run_re():
  4. pattern = 'ERROR'
  5. re_obj = re.compile(pattern)
  6. infile = open('/home/udb/jt.txt', 'r')
  7. match_count = 0
  8. lines = 0
  9. for line in infile:
  10. match = re_obj.search(line)
  11. if match:
  12. match_count += 1
  13. lines += 1
  14. return (lines, match_count)
  15. if __name__ == "__main__":
  16. lines, match_count = run_re()
  17. print 'LINES--->', lines
  18. print 'MATCHES--->', match_count

常用的正则表达式方法有findall(), finditer(), match(), search()

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。