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.