Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex for masking data

Tags:

regex

replace

I am trying to implement regex for a JSON Response on sensitive data.

JSON response comes with AccountNumber and AccountName.

Masking details are as below.

accountNumber Before: 7835673653678365
accountNumber Masked: 783567365367****

accountName Before : chris hemsworth
accountName Masked : chri* *********

I am able to match above if I just do [0-9]{12} and (?![0-9]{12}), when I replace this, it is replacing only with *, but my regex is not producing correct output.

How can I produce output as above from regex?

like image 939
Karan Chaudhary Avatar asked Oct 18 '25 06:10

Karan Chaudhary


1 Answers

If all you want is to mask characters except first N characters, don't think you really a complicated regex. For ignoring first N characters and replacing every character there after with *, you can write a generic regex like this,

(?<=.{N}).

where N can be any number like 1,2,3 etc. and replace the match with *

The way this regex works is, it selects every character which has at least N characters before it and hence once it selects a character, all following characters also get selected.

For e.g in your AccountNumber case, N = 12, hence your regex becomes,

(?<=.{12}).

Regex Demo for AccountNumber masking

Java code,

String s = "7835673653678365";
System.out.println(s.replaceAll("(?<=.{12}).", "*"));

Prints,

783567365367****

And for AccountName case, N = 4, hence your regex becomes,

(?<=.{4}).

Regex Demo for AccountName masking

Java code,

String s = "chris hemsworth";
System.out.println(s.replaceAll("(?<=.{4}).", "*"));

Prints,

chri***********
like image 50
Pushpesh Kumar Rajwanshi Avatar answered Oct 21 '25 00:10

Pushpesh Kumar Rajwanshi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!