style nitpick: moving the content of the if block to its own lines as follow, would be more readable imo:

    if (change_the_first_match_only) {
        res.append(cs + curoffset, len - curoffset);
        break;
    }

at least add spaces before and after the '+'