Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Match everything other than a specific pattern in a number

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading