I am trying to match everything in a phone number other than a specific pattern (e.g. In the number "07440359359" is there a way to match everything other than "359").
My main aim with this is to be able to replace the last digit in the number that is not in the pattern (e.g. with "07440359359" the desired output is "0744*359359").
I’ve come up with this pattern so far '^(?!.*(359))' but it does not match everything other than the pattern.
Any ideas would be greatly appreciated! 🙂
>Solution :
I think you’d want:
\d((?:359)*)$
See an online demo
\d– A single digit;((?:359)*)– A 1st capture group to match ‘359’ (greedy);$– End string anchor.
Replace with *\1
import re
s = "07440359359"
print(re.sub(r'\d((?:359)*)$', r'*\1', s))
Prints:
0744*359359