Marco
Marco

Reputation: 37

Regex to validate that every digit is different from each other

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.

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]");
    }
}

Upvotes: 0

Views: 59

Answers (2)

Youcef LAIDANI
Youcef LAIDANI

Reputation: 59950

@Vinz's answer is perfect, but if you insist on using regex, then you can use:

public static boolean validate(String s) {
    return s.matches("(?!.*(.).*\\1)[0-9]+");
}

Upvotes: 3

Vinz
Vinz

Reputation: 477

You don't need to use regex for that. You can simply count the number of unique characters in the String and compare it to the length like so:

public static boolean validate(String s) {
    return s.chars().distinct().count() == s.length();
}

Upvotes: 1

Related Questions