1

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
2
  • What language? That will be crucial to give a complete answer. Commented Apr 4, 2014 at 22:34
  • See my answer, just saw your C# preference after writing something in JS. Let me know if you really need a C#/JS example, but all you really need to do is make my regular expression dynamic based on n and m. Commented Apr 4, 2014 at 22:41

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.