Home > Back-end >  Partially mask data of a group of number using regex
Partially mask data of a group of number using regex

Time:10-05

I would like to partially mask data using regex. Here is the input :

123-12345-1234567

And here is what I'd like as output :

1**-*****-*****67

I figure out how to replace for the last group but I don't know to do for the rest of the data.

String s = "123-12345-1234567";
System.out.println(s.replaceAll("\\d(?=\\d{2})", "*")); // output is *23-***45-*****67

Also, I'd like to use only regex because I have different type of data, so different type of mask. I don't want to create functions for each type of data.

For example :

AAAAAAAAA // becomes ********AA

12334567 // becomes 123******

Thanks for your help !

CodePudding user response:

We can use the following regex replacement approach:

String input = "123-12345-1234567";
String output = input.substring(0, 1)  
                input.substring(1, input.length()-2).replaceAll("\\d", "*")  
                input.substring(input.length()-2);
System.out.println(output);  // 1**-*****-*****67

Here we concatenate together the first digit, followed by the middle portion with all digits replaced by *, along with the final two digits.

Edit: A pure regex solution, which, however, is more lines of code than the above and might be less performant.

String input = "123-12345-1234567";
String pattern = "^(\\d)(.*)(\\d{2})$";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(input);
if (m.find()) {
    String output = m.group(1)   m.group(2).replaceAll("\\d", "*")   m.group(3);
    System.out.println(output);  // 1**-*****-*****67
}

CodePudding user response:

You can define a method to mask using a pair of regexs.

pattern1 is a pattern to extract the character string to be masked. pattern2 is the pattern that should be replaced with "*" for the extracted string.

public static String mask(String input, String pattern1, String pattern2) {
    return Pattern.compile(pattern1).matcher(input)
        .replaceAll(m -> m.group().replaceAll(pattern2, "*"));
}

public static void main(String[] args) throws IOException {
    System.out.println(mask("123-12345-1234567", "(?<=.).*(?=..)", "\\d"));
    System.out.println(mask("AAAAAAAAA", ".*(?=..)", "."));
    System.out.println(mask("12334567", "(?<=...).*", "."));
}

output:

1**-*****-*****67
*******AA
123*****
  • Related