I have to validate strings with specific conditions using a regex statement. The condition is that every digit is different from each other. So, 123 works but not 112 or 131.
So, I wrote a statement which filters a string according to the condition and prints true once a string fullfies everything, however it only seems to print “true” altough some strings do not meet the condition.
JavaScript
x
public class MyClass {
public static void main(String args[]) {
String[] value = {"123","951","121","355","110"};
for (String s : value){
System.out.println(""" + s + """ + " -> " + validate(s));
}
}
public static boolean validate(String s){
return s.matches("([0-9])(?!1)[0-9](?!1)[0-9]");
}
}
Advertisement
Answer
@Vinz’s answer is perfect, but if you insist on using regex, then you can use:
JavaScript
public static boolean validate(String s) {
return s.matches("(?!.*(.).*\1)[0-9]+");
}