fdhfgh 发表于 2017-4-28 09:31:53

Python中使用正则表达式

  关键字: python ,正则表达式
《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()
页: [1]
查看完整版本: Python中使用正则表达式