def line_number_in_contents(contents, regex, default=1):
    """Find the line number where regex first occurs inside contents.

    If regex has a matching group, the line number of the start of the
    matching group will be returned.  If the regex is not found,
    'default' is returned.
    """
    m = regex.search(contents)
    if not m:
        return default

    if m.groups():
        startpos = m.start(1)       # start of group 1 (the paren section)
    else:
        startpos = m.start(0)       # start of the entire regexp

    return contents.count('\n', 0, startpos) + 1