def regex_unanchor(regexp):
    """
    ES regexps are anchored, so adding .* is necessary at the beginning and
    end to get a substring match. But we want to skip that if front/end
    anchors are explicitly used.

    Also avoid doubling up wildcards, in case the regexp engine is not smart
    about backtracking.
    """

    if regexp.startswith('^'):
        regexp = regexp.lstrip('^')
    elif not regexp.startswith('.*'):
        regexp = '.*' + regexp
    if regexp.endswith('$'):
        regexp = regexp.rstrip('$')
    elif not regexp.endswith('.*'):
        regexp += '.*'
    return regexp