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.
(?<!\d{3})\d
Here is the link for regex101
CodePudding user response:
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.