Share this page 

Apply a mask to StringTag(s): String/Number

public class TestMF {
   public static String value = "A1234B567Z";
   public static String mask = "A-AAAA-AAAA-A";

   public static void main(String args[]) {
     try {
       // output : A-1234-B567-Z
     catch (java.text.ParseException e) {

   public static String formatString(String string, String mask)
       throws java.text.ParseException {
     javax.swing.text.MaskFormatter mf =
          new javax.swing.text.MaskFormatter(mask);
     return mf.valueToString(string);

NOTE : Since this is Swing class, it is designed to be used in conjunction with a JFormattedTextField.

MaskFormatter format = new MaskFormatter("A##-##");
JFormattedTextField textField = new JFormattedTextField( format );
The possible mask values are
Character   Description
#           Any valid number, uses Character.isDigit .
'           Escape character, used to escape any of
            the special formatting characters.
U           Any character ( Character.isLetter ).
            All lowercase letters are mapped to upper case.
L           Any character ( Character.isLetter ).
            All upper case letters are mapped to lower case.
A           Any character or number
            ( Character.isLetter or Character.isDigit )
?           Any character ( Character.isLetter ).
*           Anything.
H           Any hex character (0-9, a-f or A-F).