javaregexreplaceall

Java regular expression for masked alphanumeric codes


I need a help to use or build a regular expression to mask alphanumeric with *.

I tried it with this expression, but it doesn't work correctly when it has zeros in the middle of the string:

(?<=[^0].{3})\w+(?=\w{4})

Live samples: https://www.regexplanet.com/share/index.html?share=yyyyf47wp3r

Input Output
0001113033AA55608981 0001113*********8981
23456237472347823923 2345************3923
00000000090000000000 0000000009000***0000
09008000800060050000 09008***********0000
AAAABBBBCCCCDDDDEEEE AAAA************EEEE
0000BBBBCCCCDDDDEEEE 0000BBBB********EEEE

The rules are:

  1. The first 4 that are not zeros, and the last 4 a must be displayed.
  2. Leading zeros are ignored, but not removed or replaced.

Solution

  • You can capture initial zeros and 3 alhpanumeric chars right after them in one group, the middle part into a second group, and then the last 4 alphanumeric chars into a third group, then only replace each char in the second group.

    Here is an example (Java 11 compliant):

    String text = "0001113033AA55608981";
    Matcher mr = Pattern.compile("^(0*\\w{4})(.*)(\\w{4})$").matcher(text);
    text = mr.replaceFirst(m -> m.group(1) + "*".repeat(m.group(2).length()) + m.group(3));
    System.out.println(text); // => 0001113**********8981
    

    See the Java demo.

    The regex matches

    Java 8 compliant version:

    String text = "0001113033AA55608981";
    Matcher m = Pattern.compile("^(0*\\w{4})(.*)(\\w{4})$").matcher(text);
    StringBuffer result = new StringBuffer();
    while (m.find()) {
        m.appendReplacement(result, m.group(1) + String.join("", Collections.nCopies(m.group(2).length(), "*")) + m.group(3));
    }
    m.appendTail(result);
    System.out.println(result.toString());
    

    See the Java code demo online.

    But you may just use

    String text = "0001113033AA55608981";
    Matcher m = Pattern.compile("^(0*\\w{4})(.*)(\\w{4})$").matcher(text);
    String result = "";
    if (m.matches()) {
        result = m.group(1) + String.join("", Collections.nCopies(m.group(2).length(), "*")) + m.group(3);
    }
    System.out.println(result);