vendredi 25 août 2017

Java Regex Match and Replace matched group with characters of same length

So I want to match credit card numbers and mask them in 6*4 format. So that only first 6 and last 4 characters will be visible. The characters between will be '*'. I tried to figure it out with a MASK like;

private static final String MASK = "$1***$3";
matcher.replaceAll(MASK);

But could not find out the way to give me back equal length of stars in the middle as the group $2.

Then I implemented the below code and it works. But what i want to ask if there is a shorter or easier way to do this. Anyone knows it?

private static final String HIDING_MASK = "**********";
private static final String REGEX = "\\b([0-9]{6})([0-9]{3,9})([0-9]{4})\\b";
private static final int groupToReplace = 2;

private String formatMessage(String message) throws NotMatchedException {
    Matcher m = Pattern.compile(REGEX).matcher(message);

    if (!m.find()) throw new NotMatchedException();
    else {
        StringBuilder maskedMessage = new StringBuilder(message);
        do {
            maskedMessage.replace(m.start(groupToReplace), m.end(groupToReplace), 
                    HIDING_MASK.substring(0, (m.end(groupToReplace) - m.start(groupToReplace))));

        } while(m.find(m.end()));

        return maskedMessage.toString();
    }
}

Aucun commentaire:

Enregistrer un commentaire