Home > front end >  How to check every alphabet character present in string using regex?
How to check every alphabet character present in string using regex?

Time:02-15

I want to check that using regex only, every alphabetic character must be present in string atleast once if string contains all alphabets then it should print true otherwise false.

  1. abcdefghijklmnopqrstuvwxyz -> true
  2. rsstuadefdghihvawfxjryhzhkjabcjklmnopq -> true
  3. 12345abcd13efghijklmnopqrstuvwxyz -> true
  4. abcxyz124 -> false

CodePudding user response:

We can do this in two steps. First, sort the string alphabetically by characters. Then, remove duplicate letters and non letters, and assert that what remains is the ABC...XYZ string:

List<String> inputs = Arrays.asList(new String[] {
    "abcdefghijklmnopqrstuvwxyz",
    "rsstuadefdghihvawfxjryhzhkjabcjklmnopq",
    "12345abcd13efghijklmnopqrstuvwxyz",
    "abcxyz124"
});

for (String input : inputs) {
    input = input.toUpperCase().replaceAll("[^A-Z]", "");
    String sorted = input.chars()
        .sorted()
        .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
        .toString();
    sorted = sorted.replaceAll("(.)\\1 ", "$1");
    if (sorted.equals("ABCDEFGHIJKLMNOPQRSTUVWXYZ")) {
        System.out.println("MATCH    => "   input);
    }
    else {
        System.out.println("NO MATCH => "   input);
    }
}

This prints:

MATCH    => ABCDEFGHIJKLMNOPQRSTUVWXYZ
MATCH    => RSSTUADEFDGHIHVAWFXJRYHZHKJABCJKLMNOPQ
MATCH    => ABCDEFGHIJKLMNOPQRSTUVWXYZ
NO MATCH => ABCXYZ

CodePudding user response:

I think this is cheaper than a solution involving sorting and regular expressions. Instead we have an array of booleans and set each one as we find a letter:

public static void main(String[] args) {
        List<String> inputs = Arrays.asList(new String[]{
                "abcdefghijklmnopqrstuvwxyz",
                "rsstuadefdghihvawfxjryhzhkjabcjklmnopq",
                "12345abcd13efghijklmnopqrstuvwxyz",
                "abcxyz124"
        });
        for (String s : inputs) {
            if (allAlphas(s)) {
                System.out.println("MATCH    => "   s);
            } else {
                System.out.println("NO MATCH => "   s);
            }
        }

    }

    static boolean allAlphas(String s) {
        boolean[] present = new boolean['z' - 'a'];
        for (int c : s.toLowerCase().toCharArray()) {
            int index = c - 'a';
            if (index < present.length && index >= 0) {
                present[index] = true;
            }
        }

        for (boolean b : present) {
            if (!b)
                return false;
        }
        return true;
    }
  • Related