Capture group via regex; then run a different regex on captured group
Question: I have a log file that's filled with run time information for a program. If it
fails it generates a typical python stacktrace.

I'd like to extract the whole stack trace, trigged by 'Traceback (most recent
call last):' into a regex group, and then run another separate regex to grab
the last line, usually something like KeyError: Something blah blah.

I have two questions that I have not been able to find answers on, is it
possible to use regex to find the Traceback line, and if it exists grab
everything from that line to the end of my file?

And if so, can I run a different regex on a captured regex group?


Answer: This should be the most obvious. Try always to give (code) examples about the
circumstances in this case for example your concrete log structure. Checkout
the [regex](https://docs.python.org/2/library/re.html) documentation.

    
    
    import re
    
    test = """
    some stuff
    Traceback (most recent call last):
      File "x.py", line x, in <module>
        raise KeyError("foo")
    KeyError: foo
    some stuff
    Traceback (most recent call last):
      File "y.py", line y, in <module>
        raise KeyError("bar")
    KeyError: bar
    some other stuff
    """
    
    match = re.findall(ur"^Traceback \(most recent call last\):\n(.*?^KeyError: (.+?)$)$", test, re.DOTALL|re.MULTILINE)
    for traceback, error in match:
        print "\n".join(a.strip() for a in traceback.split("\n"))
        print error.strip()
    

Hint: .*? is a non-greedy match, that means it tries to match as less as
possible. Otherwise it matches stuff between two tracebacks.

Results in:

    
    
    File "x.py", line x, in <module>
    raise KeyError("foo")
    KeyError: foo
    foo
    File "y.py", line y, in <module>
    raise KeyError("bar")
    KeyError: bar
    bar
    

