Search code examples
javaregexregular-language

check a int/string contains specific digits in it using regex


I have a string/integer X: 912035374356789

i want to check if X contains : 1, 2, 3, 4, 5, 6, 7, 8, 9, 0

occurrence order is not matter

How do check it using regular expression. if there is any algorithm please mention, because i want to do it in minimum time complexity

Example
ex1: 61243456092 //false 7 & 8 not present
ex2: 864123456789 //false 0 is not present
ex3: 987601234567 //true all present

Solution

  • If the string contains only digits then you can count the number of unique digits in it

    long count = string.chars().distinct().count();
    

    and check if count is 10

    Example

    String ex1 = "61243456092";
    String ex2 = "864123456789";
    String ex3 = "987601234567";
    
    System.out.println(ex1.chars().distinct().count());
    System.out.println(ex2.chars().distinct().count());
    System.out.println(ex3.chars().distinct().count());
    

    yields

    8
    9
    10