Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RegEx: Allow value only once

Tags:

java

regex

I have a string of numbers and each number can appear either zero or one time in the string. Can I validate this via RegEx? I could do something like check the character array for duplicates, but would prefer to stick to my normal validation routine.

The following should return "Match"

String thisItemText = "12679";
if(!thisItemText.matches("[1245679]*")) {
    System.out.println("No Match");
} else {
    System.out.println("Match");
}

The following should return "No Match" (note the double "2")

String thisItemText = "122679";
if(!thisItemText.matches("[1245679]*")) {
    System.out.println("No Match");
} else {
    System.out.println("Match");
}
like image 457
Robert Avatar asked Dec 22 '22 03:12

Robert


2 Answers

The regex (\d).*\1 will match if there's a repeated digit.

like image 112
MRAB Avatar answered Dec 24 '22 00:12

MRAB


Try this pattern:

"(?<=([0-9]))(?:(?!\\1).)*\\1(?!\\1)"

will match a string that has any repeating digits. So if it does not match then it does not have any repeating digits.

like image 25
ʞɔıu Avatar answered Dec 24 '22 01:12

ʞɔıu