Krzysztof Tkacz
Krzysztof Tkacz

Reputation: 488

Mask string with another pattern string

I'd like to mask numbers according to pattern. If number is 22123123123 and pattern is xxxxx***xxx the result of masking should be 22123***123. I wrote a code:

private String maskNumberWithPattern(String number) {
    char[] pattern = "xxxxx***xxx".toCharArray();
    char[] numberInput = number.toCharArray();
    StringBuffer stringBuffer = new StringBuffer();
    for (int i = 0; i < pattern.length; i++) {
        if(pattern[i] == '*') {
            stringBuffer.append("*");
        } else {
            stringBuffer.append(numberInput[i]);
        }
    }
    return stringBuffer.toString();
}

Is there some standard api method to achieve that?

Upvotes: 1

Views: 781

Answers (1)

rudi
rudi

Reputation: 791

It's not clear from your code how your pattern behaves exactly. For example, what should happen if the input String is longer than your pattern? Is there a chance that the pattern does not match? Etc. I don't know such thing...

I guess wildcard patterns or regular expression is the easiest thing you can get here:

private static String maskNumberWithPattern(String number) {
    Pattern pattern = Pattern.compile("(\\d{5})(\\d*)(\\d{3})");
    Matcher matcher = pattern.matcher(number);
    if (matcher.matches()) {
        String group = matcher.group(2);
        return matcher.group(1) + StringUtils.repeat('*', group.length()) + matcher.group(2);
    }
    else {
        return number;
    }
}

Upvotes: 1

Related Questions