Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

@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]+");
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading