Home > Blockchain >  Regex to validate that every digit is different from each other
Regex to validate that every digit is different from each other

Time:11-06

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

CodePudding user response:

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

CodePudding user response:

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();
}
  •  Tags:  
  • java
  • Related