Question

It may be asked already but I need regex pattern for mask replacement below (n characters before the end with length of m)

n=3
m=4
In1Ex:ABCDEFG12345678 -> Out1Ex: ABCDEFG1****678
In2Ex:GFEDCBA876453 -> Out2Ex: GFEDCB****453


n=6
m=2
In3Ex:ABCDEFG12345678910 -> Out3Ex: ABCDEFG123**678910
In4Ex:GFEDCBA87645321 -> Out4Ex: GFEDCBA8**45321
Was it helpful?

Solution

Something like this expression will get you started:

.{4}(?=.{3}$)
.{2}(?=.{6}$)

This matches any 4 (2) characters followed by the last 3 (6) characters. Depending on the language, you can replace based on dynamic lengths. In PHP:

$n = 3;
$m = 4;

$string = 'ABCDEFG12345678';
echo preg_replace('/.{' . $m . '}(?=.{' . $n . '}$)/', str_repeat('*', $m), $string);
// ABCDEFG1****678

More in depth RegExp explanation:

.{4}         # matches any 4 characters
(?=          # start a "lookahead"
  .{3}       # matches any 3 characters
  $          # matches the end of the string
)            # end the "lookahead"

This means that you will find whatever 4 characters are followed by 3 characters and the end of the string. Lookaheads aren't returned as a match, so you will still just be replacing those 4 characters matched.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top