---
title: "Python中使用正则表达式"
author: "flynewton"
date: "2011-01-30T14:02:23Z"
tags: []
categories: ["编程语言"]
slug: "python"
draft: false
lastmod: "2011-01-30T14:02:23Z"
id: 899787
url: "https://flynewton.iteye.com/blog/899787"
---

**关键字：** [python](http://www.oschina.net/home/search?scope=blog&q=python) , [正则表达式](http://www.oschina.net/home/search?scope=blog&q=%E6%AD%A3%E5%88%99%E8%A1%A8%E8%BE%BE%E5%BC%8F)

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

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

[源码](http://my.oschina.net/flynewton/blog/8900)[打印](http://my.oschina.net/flynewton/blog/8900)[？](http://my.oschina.net/flynewton/blog/8900)

01. #!/usr/bin/env python
02. import re
03. def run\_re():
04. pattern = 'ERROR'
05. re\_obj = re.compile(pattern)
06. infile = open('/home/udb/jt.txt', 'r')
07. match\_count = 0
08. lines = 0
09. 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---&gt;', lines
18. print 'MATCHES---&gt;', match\_count

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