fork download
  1. import re
  2.  
  3. pattern = r"(?<!\S)((?:\+1)?)(\d{3})(\d{5})(?!\S)|\d+"
  4.  
  5. s = ("Mr.X has 23 apples and 59 oranges, his business partner from Colorado staying staying in hotel with phone number +188991234 and his wife and kids are staying away from him\n\n"
  6. "This is a tel 12345678 and this is 1234567 123456789")
  7.  
  8. result = re.sub(
  9. pattern,
  10. lambda x: x.group(1) + x.group(2) + "*" * len(x.group(3)) if x.group(2) else "0" * len(x.group()),
  11. s)
  12. print(result)
Success #stdin #stdout 0.02s 9560KB
stdin
Standard input is empty
stdout
Mr.X has 00 apples and 00 oranges, his business partner from Colorado staying staying in hotel with phone number +1889***** and his wife and kids are staying away from him

This is a tel 123***** and this is 0000000 000000000