Regular expression to check in a word for repeated letter and prevent input of character or symbol

Viewed 95

Am just trying to write a method in java that will use regular expression to check if a word does not contain any repeated letter whether "AAA" or "Aba" or "aa" and does not include any special characters like $, !, &, ....

Here is what I tried so far.

public boolean checkWord(String word) {
        Pattern regex = Pattern.compile("([a-zA-Z0-9])\\1{1}");
        Matcher match = regex.matcher(word);
        if (match.find()) {
            return true;
        }
            return false;
        }
    }
3 Answers

You can use this:

public boolean checkWord(String word) {
    Pattern regex = Pattern.compile("([a-zA-Z0-9]).*\\1|[^a-zA-Z0-9]");
    Matcher match = regex.matcher(word);
    return !match.find();
}

Please, notice that I basically switched your true and false.

For an alternate approach, here's a short method (in Java 9+) to do this without RegEx. It uses a set to keep track of characters it needs to reject.

Rather than checking if the character needs to be rejected using set.contains() then also set.add() later, I just call set.add() and use the result to catch if the character was already in the set. This way the set only needs to be searched once.

For each character in the word I convert it to lower case, try to add it to the set, if successful then continue with the next char, if unsuccessful then return true since this matches a string that needs to be rejected (you could negate this if needed).

/** Checks if a word contains any specified special characters, or any re-used character */
public static boolean checkWord(String word) {
    final Set<Character> set = new HashSet<>(Arrays.asList('$', '!', '&'));
    return word.chars().anyMatch(i -> !set.add(Character.toLowerCase((char) i)));
}

public static void main(String[] args) {
    String[] words = { "AAA", "Aba", "aa", "abc&def", "$omething", "exciting!", "abcd", };
    for (String word : words) {
        System.out.println(checkWord(word) + " : " + word);
    }
}

It's still a bit unclear to me when you want the method to return true/false, but I think the main idea can be solved by the code below, without regex:

    public boolean checkWord(String word) {
        final Set<Character> set = new HashSet<>();
        boolean passed = false;
        //using toLowerCase because `a` should be equal to `A`
        final char[] characters = word.toLowerCase().toCharArray();
        for (char c : characters) {
            //if a special character is found, return false
            if (! Character.isLetterOrDigit(c)) {
                return false;
            }
            
            //if caracter is in the set, it's a re-occurence
            if (set.contains(c)) {
                passed = true; //can't return, must check rest of string for special characters
            }
            //added to check re-occurrence
            set.add(c);
        }

        return passed;
    }
Related