Then I modified the regex expression:
mascara.matches("\D{0,4}|\D{0,4}\d{0,2}|\D{0,4}\d{0,3}");
My test has answered all the cases, including for the old plates, but if anyone finds any divergence, I will be grateful to let me know.
import android.text.Editable;
import android.text.InputFilter;
import android.text.InputType;
import android.text.TextWatcher;
import android.widget.EditText;
import android.widget.Toast;
public class PlacaUtils {
HomeActivity context;
public static String unmask(String s) {
return s.replaceAll("[.]", "").replaceAll("[-]", "")
.replaceAll("[/]", "").replaceAll("[(]", "")
.replaceAll("[)]", "");
}
public static TextWatcher insert(final EditText ediTxt) {
return new TextWatcher() {
String mask = "UUU-####";
boolean isUpdating;
String old = "";
public void onTextChanged(CharSequence s, int start, int before,
int count) {
ediTxt.setFilters(new InputFilter[]{new InputFilter.AllCaps()});
String str = PlacaUtils.unmask(s.toString());
String mascara = "";
if (isUpdating) {
old = str;
isUpdating = false;
return;
}
int i = 0;
for (char m : mask.toCharArray()) {
if ((m != '#' && m != 'U') && str.length() > old.length()) {
mascara += m;
continue;
}
try {
Character c = str.charAt(i);
if (mascara.length() < 3) {
if (Character.isLetter(c)) {
mascara += str.charAt(i);
}
} else if (mascara.length() >= 3) {
if (Character.isDigit(c)) {
mascara += str.charAt(i);
} else if (Character.isLetter(c)) {
boolean b = mascara.matches("\D{0,4}|\D{0,4}\d{0,2}|\D{0,4}\d{0,3}");
if (b) {
mascara += str.charAt(i);
}
}
}
} catch (Exception e) {
break;
}
i++;
}
isUpdating = true;
if (str.length() < 3) {
ediTxt.setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
} else if (str.length() >= 3) {
ediTxt.setInputType((InputType.TYPE_CLASS_TEXT));
}
ediTxt.setText(mascara);
ediTxt.setSelection(mascara.length());
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void afterTextChanged(Editable s) {
}
};
}
public static boolean isValid(final String placa) {
if (StringUtils.isEmpty(placa)) {
return false;
}
if (placa.matches("[A-Z]{3}[0-9][A-Z][0-9]{2}")) {
return true;
} else {
return false;
}
}
public static String masked(String placa) {
placa = unmask(placa);
placa = placa.substring(0, 3) + "-" + placa.substring(3, 7);
return placa;
}
}