I'm trying to create a regex that will allow only digits followed by only one character after every digit within a Textfield
Regex that needs to match - \\d*\\+{1}
Regex in case it does not match - [^\\d*\\+){1}] will replace with "" (removes everything else)
final String regexFinalInteger = "\\d*\\+{1}";
numberElements.textProperty().addListener((observable, oldValueE, newValueE) -> {
if (!newValueE.matches(regexFinalInteger)) {
numberElements.setText(newValueE.replaceAll("[^\\d*\\+){1}]", ""));
}
});
I will expect an output of 122+1+3 but the actual output can be 1++2+++4+123 (multiple +)
If I understood correctly, you want to replace multiple +
s with only one.
I believe this would enable what you're looking for:
String regex = "[+](?=[+])";
String text = "122+1+3";
assertEquals("122+1+3", text.replaceAll(regex, ""));
text = "1++2+++4+123";
assertEquals("1+2+4+123", text.replaceAll(regex, ""));
That is my first Java program, I'm sorry if it offends someone.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.