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

replace the alphanumeric numbers with X

I am trying to replace the alphanumeric text with X for numbers but my text also has got other numbers which are not alphanumeric and those not to be replaced. I could able to locate the alphanumeric using the code below but unable to replace them.

Code

result = re.sub(r'\S*\d+\S*,'',text)

text = my text contains of the 33109 following values RT3123SO55 and also with certain numbers godwil_5708 and 323stwe and 8y9yc2 456453

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

expected output is

my text contains of the 33109 following values RTXXXXSOXX and also with certain numbers godwil_XXXX and XXXstwe and XyXycX 456453

>Solution :

I think you could try to use PyPi’s regex library instead:

\b\d+(?:\.\d+)?\b(*SKIP)(*F)|\d

See an online demo


  • \b\d+(?:\.\d+)?\b – First match what we don’t want. In this case I matched any 1+ digits with optional decimals inbetween word-boundaries;
  • (*SKIP)(*F) – Forget what we matched and exclude it from the final results;
  • | – Or;
  • \d – Any single digit.

import regex as re
s = 'my text contains of the 33109 following values RT3123SO55 and also with certain numbers godwil_5708 and 323stwe and 8y9yc2 456453'
print(re.sub(r'\b\d+(?:\.\d+)?\b(*SKIP)(*F)|\d', '*', s))

Prints:

my text contains of the 33109 following values RT****SO** and also with certain numbers godwil_**** and ***stwe and *y*yc* 456453
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