#!/usr/bin/env python2.5 # -*- coding: UTF-8 -*- #***************************************************************************\ #* Copyright (C) 2008 by Nicolai Spohrer, * #* nicolai@xeve.de * #* * #* This program is free software; you can redistribute it and/or modify * #* it under the terms of the GNU General Public License as published by * #* the Free Software Foundation; either version 3 of the License, or * #* (at your option) any later version. * #* * #* This program is distributed in the hope that it will be useful, * #* but WITHOUT ANY WARRANTY; without even the implied warranty of * #* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * #* GNU General Public License for more details. * #* * #* You should have received a copy of the GNU General Public License * #* along with this program; if not, see * #* or write to the * #* Free Software Foundation, Inc., * #* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * #*************************************************************************** #* Grep-ähnliche Funktionen für Python * #*************************************************************************** import re def grep( pattern, # RegEx für das Gesuchte context # Liste, die die einzelnen Zeilen enthält. # Erhält man zB durch string.split("\n") ): """ Gibt das erste Element der Liste zurück, auf die der reguläre Ausdruck zutrifft. """ patternprog = re.compile(pattern) # Kompilierter RegEx for line in context: # Für jedes Element der Liste a_match = patternprog.search(line) # Trifft der RegEx # auf die Zeile zu? if (a_match): # Wenn ja return line # Gib die richtige Zeile zurück def grep_all( pattern, # RegEx für das Gesuchte context # Liste, die die einzelnen Zeilen enthält. # Erhält man zB durch string.split("\n") ): """ Gibt alle Elemente der Liste zurück, auf die der reguläre Ausdruck zutrifft. """ patternprog = re.compile(pattern) # Kompilierter RegEx matches = [] for line in context: # Für jedes Element der Liste a_match = patternprog.search(line) # Trifft der RegEx # auf die Zeile zu? if (a_match): # Wenn ja matches.append(line) # Hänge die Zeile an die Ergebnisliste an return matches