def re_wrap(p):
    """
    Wrap a regular expression if necessary, i.e., if it contains unescaped '|' 
    in the outermost level.
    """
    escaped = False
    level = 0
    for c in p:
        if c == '\\':
            escaped = not escaped
        elif c == '(' and not escaped:
            level += 1
        elif c == ')' and not escaped:
            level -= 1
        elif c == '|' and not escaped:
            if level == 0:  # outmost level, must wrap
                p = '(' + p + ')'
                break
        else:
            escaped = False
    return p