import re


def build_intro_pattern(genus, species=r'(?:x\\)?[a-z\-]+', subspecies=''):
    """Build a regex pattern for a species introduction.

    Paramters:
        genus - of the species
        species - specific species to look for (defaults to any)
        subspecies - the subspecies to look for (defaults to empty string)

    The regex pattern has three potenital subgroups.

    1 - the genus name
    2 - the species name
    3 - the subspecies name (if specified)
    """
    # --- Species Introduction ---
    #
    # Relies on the assumption that a species introduction is formatted as:
    #
    #  n[a]*. Species name {arbitrary text} [(subsp|var). name] {arbitrary text}
    #
    # Where n is an arbitrary natural and a is an arbitrary alphabetical
    # character.

    # This will match the "n[a]*" part of the inroduction
    pattern = r'^\d+'

    # if the subspecies was specified, we know there must be alphabetical
    # numbering on them
    if subspecies:
        pattern += r'[a-z]+'

    if 'x\\' in species and '[a-z' not in species:
        species = species.replace('x\\', 'x\\\\')

    # This will now match the 'n[a]*. Species name' part of the introduction
    pattern += r'\.[ ]*('+genus+') ('+species+')'

    # if the subspecies was specified, we know there must be some descriptor
    # followed by 'subsp.' and the subspecies name
    #
    # i.e. the '{arbitrary text} [(subsp|var). name] {arbitrary text}' part of
    # the introduction is now matched
    if subspecies:
        pattern += r'.*?(?:subsp|var)\.\s*('+subspecies+')'

    return re.compile(pattern, flags=re.MULTILINE|re.DOTALL)