import re
regex = re.compile(r"(?<=^\d*)\d{3}(?=\d{2,}$)", flags=re.MULTILINE)
test_str = ("9871234567\n"
"98712345678\n"
"987123456789\n"
"9871234567890\n\n"
"abc 9871234567")
subst = "xxx-"
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