您的位置:首页 > 编程语言 > Python开发

Python中使用正则表达式

2012-07-22 17:39 537 查看
转自:/article/3535286.html

《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()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: