That's a lot of code. I did a quick scan and it dos look correct, but I do
not have a high level of confidence with it. I would need more time to
review the code.
One key thing that is missing from this code (and mine) is a method of
verifiability. I would change the code so that the main part creates three
strings: the text before the number (TBN), the number (N) and the text after
the number (TAN). At the very end of the code I would return trim(TBN+"
"+TBA) for the text, N for the number.
By combining the three strings, trim(trim(TBN+" "+N)+" "+TAN) as a
verification string you can check it against the original string. If they do
not match, then there is a problem with the code and you should display an
error message with the problem string.