def remove_pattern(p, s, ignore_nl=True):
    """Removes a pattern from a string.

    The function removes the first occurence of the pattern from a string. It
    returns a tuple of the resulting string and the matching object (or
    ``None``, if the pattern did not match).

    :param re.regex p: pattern to be removed
    :param str s: string to be searched
    :param bool ignore_nl: When ``True``, newlines in the string are ignored
        during the pattern search. The returned string will still contain all
        newline characters outside of the matching part of the string, whereas
        the returned matching object will not contain the newline characters
        inside of the matching part of the string.
    :returns: the result string and the match object or ``None`` if
        search failed
    :rtype: tuple of str and (re.match or None)

    Example:
        >>> r, m = remove_pattern(re.compile("XXX"), 'ab\\ncXX\\nXdefXX\\nX')
        >>> r
        'ab\\ncdefXX\\nX'
        >>> m.string[m.start():m.end()]
        'XXX'

    """
    if ignore_nl:
        r = s.replace('\n', '')
        has_nl = r != s
    else:
        r = s
        has_nl = False
    m = p.search(r)
    if m:
        s_start = r_start = m.start()
        s_end = r_end = m.end()
        if has_nl:
            j = 0
            for c in s:
                if c == '\n':
                    if j < r_end:
                        s_end += 1
                        if j <= r_start:
                            s_start += 1
                else:
                    j += 1
        return s[:s_start] + s[s_end:], m
    return s, None
