Für diesen Zweck vielleicht etwas zu aufgeblasen, aber trotzdem:
import sys, re
def firstMatch(regExp, text):
"""returns the first match of the python regular expression
regExp in text or None if no such match exists.
>>> firstMatch("ab*c", "acabcb")
"ac"
>>> firstMatch("p?ro", "acabcb")
"""
matOb = re.search(regExp, text)
if matOb:
retVal = matOb.group(0)
else:
retVal = None
return retVal
if __name__=="__main__":
if len(sys.argv)<3:
sys.stderr.write("Usage: firstmatch.py <re> <fname>\n")
sys.exit(1)
try:
txt = open(sys.argv[2]).read()
except IOError, msg:
sys.stderr.write("Couldn't open %s: %s\n"%(sys.argv[2],
str(msg)))
sys.exit(1)
mat = firstMatch(sys.argv[1], txt)
if mat is not None:
print mat
Demgegenüber wäre auch die lean-and-mean-Fassung denkbar, je nach Einsatzziel (dieses hier ist mehr Einwegsoftware – auf die gibts zwar noch kein Pfand, aber schön ist das trotzdem nicht):
import sys, re m = re.search(sys.argv[1], open(sys.argv[2]).read()) if m is not None: print m.group(0)
(weiterführend:) – oder, als Äquivalent des 400 PS-Motors (völlig nutzlos und gefährlich, aber man kann zumindest glauben, damit significant others zu beeindrucken – das hier basiert auf short circuit evaluation, die erst später kommt):
import sys, re sys.stdout.write([(a is not None and a.group(0)+"\n") or "" for a in [re.search(sys.argv[1], open(sys.argv[2]).read())]][0])