import re
regex = re.compile(r"\b(\d+)(?:(?:[\.\s]0+|(\.\d+)))?\s?USD")
test_str = ("123.00 USD\n"
"1234 USD\n"
"357.0 USD\n"
"456 00 USD\n"
"651USD\n"
"753.684 USD\n"
"123 456 USD\n"
"-123 USD\n"
"789.00 XXX\n"
"123.00 wrongcurrency\n"
"test string\n"
"$159")
subst = "$\\1\\2"
result = regex.sub(subst, test_str)
if result:
print(result)
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for Python, please visit: https://docs.python.org/3/library/re.html