python context sensitive regex for parsing hierchical text structure
Question: I have a string like this:

    
    
    Group 1:
    Line A
    Line B
    Line C
    Group 2:
    Line A
    Line B
    

I am wondering if it is possible to parse this with a regex with the results
being something like:

    
    
    Group: 1, Line: A
    Group: 1, Line: B
    Group: 1, Line: C
    Group: 2, Line: A
    Group: 2, Line: B
    

Here is what I have so far:

    
    
    regex = r'''(?x)
    (?<=Group\s(\d):\n)
    (?:Line\s\w+\n)*
    Line\s(\w+)
    '''
    match_iter = re.finditer(regex,test,re.M|re.S|re.I)
    for m in match_iter:
        print m.groups()
    

But this is wrong because I am only getting:

    
    
    ('1', 'C')
    ('2', 'B')
    

And I'm stuck here... any idea how I can do this? (or if it is even possible
to do with re)

EDIT: I am looking for a regex only solution because I am trying to plug this
into a light framework that will only take a regex and not arbitrary code. I
can't use anything with states etc. This means In the above code snippet I can
only change the value of 'regex'.


Answer: 
    import re
    
    regex = re.compile("(Group) (\d+)|(Line) (\w+)")
    
    INPUT = """
    Group 1:
    Line A
    Line B
    Line C
    Group 2:
    Line A
    Line B"""
    
    def main():
        group, line = None, None
        for match in regex.finditer(INPUT):
            if match.group(1):
                # found a Group
                group = match.group(2)
            else:
                # found a Line
                line = match.group(4)
                print("Group: {group}, Line: {line}".format(group=group, line=line))
    
    if __name__=="__main__":
        main()
    

returns

    
    
    Group: 1, Line: A
    Group: 1, Line: B
    Group: 1, Line: C
    Group: 2, Line: A
    Group: 2, Line: B
    

