Try this:
Code:
def replace(match, number, file_name, metadata, data):
if match:
title_open = match.group(1)
title_close = match.group(2)
between = match.group(3)
chapter_title = match.group(4).strip()
return title_open + chapter_title + title_close + between
Perhaps the problem is also that you put
\s* before the closing </a></h1>, which forces a space to appear before the anchor closes.
To debug functions, it's a good idea to enable the SIGIL_FUNCTION_REPLACE_LOGFILE environment variable; that way, you'll see the errors in the log file.