def match_rules(txt, rules):
    """Find rule that first matches in txt"""
    # Find first begin tag
    first_begin_loc = 10e100
    matching_rule = None
    for rule in rules:
        begin_tag, end_tag, func = rule
        loc = txt.find(begin_tag)
        if loc > -1 and loc < first_begin_loc:
            first_begin_loc = loc
            matching_rule = rule
    return (matching_rule, first_begin_loc)