How to mask multiple values in a String using regex in Java

Viewed 544

I am new to regex and trying to implement regex for my code. My code is receiving message String that contains few attribute that I need to mask. Now the Format of message string can be little different and masking attributes could be dynamic. Here is the example

String message1 ="details-\r\n"+
 "pin:testpin\r\n"+
 "pass:test\r\n";
String message2 = "{\"pin\":\"1234\",\"pass\":\"test\"}";

Can we write regex that works if I want to mask pin and pass both ?

1 Answers

These regular expressions are looking for pin or pass surrounded by " followed by :" and then looking to for closing " as soon as possible (.*? is non-greedy). The values get the replace by *

message2 = message2.replaceAll("\\\"pin\\\":\\\".*?\\\"", "\"pin\":\"****\"")
                   .replaceAll("\\\"pass\\\":\\\".*?\\\"", "\"pass\":\"****\"");

It has the disadvantage, that " may not be part of the values of pin or pass.

Here's a minimal test:

public class Test {
  public static void main(String[]arg) {
    String message2 = "{\"pin\":\"1234\",\"pass\":\"test\"}";
    message2 = message2.replaceAll("\\\"pin\\\":\\\".*?\\\"", "\"pin\":\"****\"")
                       .replaceAll("\\\"pass\\\":\\\".*?\\\"", "\"pass\":\"****\"");
    System.out.print(message2);
  }
}

Here's a bigger example with replacing the correct length. There are more things going on here:

import java.util.regex.*;

public class Test {
    public static void main(String[]arg) {
        //more complex
        String message1 ="details-\r\n" + "pin:testpin\r\n" + "pass:test\r\n";
        String regex1 = "(\\r\\npin:)(.*?)(\\r\\npass:)(.*?)(\\r\\n)";
        message1 = Pattern
            .compile(regex1)
            .matcher(message1)
                .replaceAll(mr -> mr.group(1) + "*".repeat(mr.group(2).length()) + mr.group(3) + "*".repeat(mr.group(4).length()) + mr.group(5));


        String message2 = "{\"pin\":\"1234\",\"pass\":\"test\"}";
        String regex2 = "(\\\")(pin|pass)(\\\":\\\")(.*?)(\\\")";       
        message2 = Pattern
            .compile(regex2)
            .matcher(message2)
                .replaceAll(mr -> mr.group(1) + mr.group(2) + mr.group(3) + "*".repeat(mr.group(4).length()) + mr.group(5));

        System.out.println(message1);
        System.out.println(message2);
    }
}

In the bigger example I'm using the replaceAll method with a lambda function in order to replace what's found. I need it in order to know the length of a matched group. That length is then used to create a string consisting of * with the length of the input.

Also I added groups in the regular expressions. Groups are parts of the regular expression surrounded by ( and ). Those groups can then be used by the matcher to more easily modify the input.

Related