0

I was looking for a way to achieve what's described here Format textfield for CPF and CNPJ except for Android and the observable returned from EditText. The following non-regex code almost gets me to where I need to be except for when I try to drop in the middle.

private String formatCpfAndPosition(String cpf) {
    int selectionStart = maskEditText.getSelectionStart();
    String formatted = cpf;
    if (inputCPFValidationListener != null) {
      int length = cpf.length();

      if ((length == 3 || length == 7 || length == 11)) {
        if (isDeleted(cpf)) {
          formatted = cpf.substring(0, length - 1);
          selectionStart -= 1;
        } else if (isLengthened(cpf)) {
          selectionStart += 1;
          if (length == 11) {
            formatted = formatted + "-";
          } else {
            formatted = formatted + ".";
          }
        }
      }
      lastCpf = formatted;
      maskEditText.setText(formatted);
      maskEditText.setSelection(selectionStart, selectionStart);
    }
    return formatted;
  }

I like the elegance offered by using regex but am unable to figure out how I'd use this. Using cpf.replaceAll("(\\d{3})(\\d{3})(\\d{3})(\\d{2})", "$1.$2.$3-$4") works only when the length of cpf reaches the 11 digit mark. While my particular case is for Android use, I believe that this can be applicable to Java as a whole.

reactor
  • 1,722
  • 1
  • 14
  • 34
  • Why you don't use the regex from the answer you linked to? It works for 4+ digits. – Oleg Feb 28 '20 at 02:46
  • @Oleg unfortunately, when I use the regex there, I get `1.2.3-4` instead of `123.4`, the latter being the preferred format. – reactor Feb 28 '20 at 03:07
  • What is your expected input and desired output? – Oleg Feb 28 '20 at 03:18
  • examples of desired input and output are: `123` -> `123.` `1234` -> `123.4` `123456` -> `123.456.` `12345678901` -> `123.456.789-01` – reactor Feb 28 '20 at 03:20
  • Don't you also need to convert `123.45.7` to `123.457` for example(if a 6 is deleted)? – Oleg Feb 28 '20 at 05:02

0 Answers0