from typing import Optional
import re


def get_entity(buffer: str) -> Optional[str]:
    """Parses the entity out of an input string

    The input is expected to be a string representing vhdl file content. If an
    entity is defined within this content, the entity block is parsed if one is
    found. If nothing is found that could be parsed, the function returns
    None. If the entity could be parsed, it is returned as a string beginning
    with "entity" and ending on "end <name>;" or "end entity;"

    Args:
        buffer (str): input string

    Returns:
        Optional[str]: entity string
    """
    # (                 begin of capture group---------------------------ENTITY
    #     entity        "entity"
    #     \s+           one or more whitespace characters
    #     \w+           one or more word characters
    #     \s+           one or more whitespace characters
    #     is            "is"
    #     .+?           any character one or more times. lazy evaluation
    #     end           "end"
    #     \s+           one or more whitespace characters
    #     \w+           one or more word characters
    #     \s*           zero or more whitespace characters
    #     ;             semicolon
    # )                 end of capture group
    m = re.search(
        r"(entity\s+\w+\s+is.+?end\s+\w+\s*;)",
        buffer,
        flags=re.IGNORECASE | re.DOTALL,  # the DOTALL may not be necessary..
    )
    if m is None:
        return None
    entity = m.group(1)
    return entity