How to set a limit of a character frequency or disable the onclick button on some conditions?
If you want to check if a string ends in a digit, you can use this
String currentTxt = display.getText().toString();
if( currentTxt.matches("^.*?\\d$") ) { // check that it ends with a number
// allow adding a + symbol at the end
display.setText(currentTxt + "+");
}
The $
in the regex matches the end of the string, and the ^
matches the front of the string. So this matches a full string with zero or more characters (.*
) followed by an ending digit (?\\d
). You can always test Regex patterns online.
In this case, a regex isn't strictly necessary though, you could also just get the last character and call isDigit
String currentTxt = display.getText().toString();
if( !currentTxt.isEmpty() && Character.isDigit(currentTxt.charAt(currentTxt.length()-1)) ) { // check that it ends with a number
// allow adding a + symbol at the end
display.setText(currentTxt + "+")
}