Which is the best way to mask a String in Java?

Viewed 6364

I want to apply a mask on a String "96506550" but I'm getting 965065-50 instead of 96506-550

//my method
public String format(String data, String mask) {
        MaskFormatter mf = new MaskFormatter(mask);        
        return mf.valueToString(data);
}

System.out.println(formatter.format("96506550","#####-###"));
2 Answers

You forgot to use

public void setPlaceholderCharacter(char placeholder)

This function sets the character to use in place of characters that are not present in the value, ie the user must fill them in. The default value is a space. This is only applicable if the placeholder string has not been specified, or does not completely fill in the mask.

That's the reason there is a single character placeholder error.

You need to handle ParseException (or throw it). Next, your Formatter won't accept input that isn't correctly formatted. Your input is eight digits, but your format expects five digits, a dash and then three digits. You could handle eight digits as a special case. Also, MaskFormatter.valueToString(Object) doesn't work like you hope (you can however validate by calling MaskFormatter.stringToValue(String) and passing that to the first function). Like,

public static String format(String data, String mask) throws ParseException {
    Pattern p = Pattern.compile("\\d{8}");
    if (p.matcher(data).matches()) {
        return data.substring(0,5) + "-" + data.substring(5);
    }
    MaskFormatter mf = new MaskFormatter(mask);
    return mf.valueToString(mf.stringToValue(data));
}
Related