import re


def get_label_and_caption(lines, i):
    """Capture any label and caption immediately after a code environment's end

    Use regex on the two lines after a code environment's end (e.g. !ec) to
    extract any label or caption. NB! This method might modify the two lines
    after the code environment by removing any label{} and caption{} commands
    :param list lines: lines of code
    :param int i: current index
    :return: label and caption
    :rtype: (str, str)
    """
    # capture any caption and label in the next two
    # lines after the end of the code environment
    label = None
    label_regex = re.compile(r"[\\]*label\{(.*?)\}")
    label_match = re.search(label_regex, "".join(lines[i + 1:i + 3]))
    if label_match:
        label = label_match.group(1)
    caption = None
    caption_regex = re.compile(r"[\\]*caption\{(.*?)\}")
    caption_match = re.search(caption_regex, "".join(lines[i + 1:i + 3]))
    if caption_match:
        caption = caption_match.group(1)
    # Remove label{} and caption{}
    if len(lines) > i + 1:
        lines[i + 1] = re.sub(label_regex, "", lines[i + 1])
        lines[i + 1] = re.sub(caption_regex, "", lines[i + 1])
    if len(lines) > i + 2:
        lines[i + 2] = re.sub(label_regex, "", lines[i + 2])
        lines[i + 2] = re.sub(caption_regex, "", lines[i + 2])
    return label, caption