Apply mascara to the Java backend

2

Does anyone know how to include a mask from a regex in a string? For example, I have the following regex String pattern = "\d{2}[/]\d{3}.\d{3}[/]\d{4}"; and a variable with the following String numeroProcesso = "010000012018"; value. I want a function that returns the following result: numeroProcessoComRegex = "01/000.001/2018" . This would be simple if my regex was not dynamic, but the same can be changed at any time.

    
asked by anonymous 13.08.2018 / 21:00

1 answer

2

One way to solve your problem would be to use the MaskFormatter class.

Example:

    public static void main(String[] args) {
        String pattern = "##/###.###/####";
        String numeroProcesso = "010000012018";
        System.out.println(format(pattern, numeroProcesso));
    }

    private static String format(String pattern, Object value) {
        MaskFormatter mask;
        try {
            mask = new MaskFormatter(pattern);
            mask.setValueContainsLiteralCharacters(false);
            return mask.valueToString(value);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }

Imports:

    import javax.swing.text.MaskFormatter;
    import java.text.ParseException;
    
13.08.2018 / 21:33