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

Regex look ahead to replace numbers

Let’s say I have a sequence of numbers for example: 28937705095, 61926197003 or even 721.095.260-84.
I would like to mask the first three numeric digits and the last two numeric digits, to something like this:

28937705095 => XXX377050XX
61926197003 => XXX261970XX
721.095.260-84 => XXX.095.260-XX

I was using javascript for this and I believe that using regular expression lookaround concepts could be a great way to solve this problem.

I managed to replace the first three numbers in the case without dots and dashes, but I don’t know where to go for the other cases.

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

(?<!\d{3})\d

Here is the link for regex101

>Solution :

You can use the following regex:

(?<=^\d{0,2})\d|\d(?=\d?$)

It works with two patterns, one for the first sequence, one for the latter.

  • (?<=^\d{0,2})\d: digit is preceeded by Positive Lookbehind, matching between no and 2 digits before
  • \d(?=\d?$): digit is followed by Positive Lookahead, matching between no and one digit after (optional digit)

Check the demo here.

Note: this solution assumes that your digits are all found together and right before or after the start/end of string.

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