Replace regular expression with proper Python function