Apply Mask to Java back-end

Asked

Viewed 1,096 times

2

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

  • I think the . of the regex was to be \\..

1 answer

2


One way to solve your problem would be by using 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;
  • the problem is precisely in this fixed Pattern, in case it needs to be regex, because the numbering format changes according to the customer’s need. In my front-end I already have this validation, but I had to implement an integration and the number comes without masking another system.

  • How does the pattern change? How does this happen?

  • I have a regex with regex of the standard number for each customer, for example for client A is 00/000.000/0000, for client B 00/0000, for C 00/00/00/0000/000. It is something legacy already, unfortunately changing the logic is very costly, so I wanted to try to find a way to do this with regex instead of the suggested Pattern.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.