84

I need a method that can tell me if a String has non alphanumeric characters.

For example if the String is "abcdef?" or "abcdefà", the method must return true.

3

9 Answers 9

170

Using Apache Commons Lang:

!StringUtils.isAlphanumeric(String)

Alternativly iterate over String's characters and check with:

!Character.isLetterOrDigit(char)

You've still one problem left: Your example string "abcdefà" is alphanumeric, since à is a letter. But I think you want it to be considered non-alphanumeric, right?!

So you may want to use regular expression instead:

String s = "abcdefà";
Pattern p = Pattern.compile("[^a-zA-Z0-9]");
boolean hasSpecialChar = p.matcher(s).find();
Sign up to request clarification or add additional context in comments.

2 Comments

I would like to avoid importing external libraries if not strictly necessary. And yes: I want à to be considered as non alphanumeric.
a side note: unrelated but just to remind StringUtils.isAlphaNumeric("abc"); returns true if the str contains only alphabets.
29

One approach is to do that using the String class itself. Let's say that your string is something like that:

String s = "some text";
boolean hasNonAlpha = s.matches("^.*[^a-zA-Z0-9 ].*$");

one other is to use an external library, such as Apache commons:

String s = "some text";
boolean hasNonAlpha = !StringUtils.isAlphanumeric(s);

3 Comments

+1: regex is here the winner I think since the OP does not really want to check for alphanumeric characters. He wants sth. like hasSpecialCharacters(String) with his own definition of "special".
That won't quite work: String.matches(...) in Java checks if the regex matches the whole string.
boolean hasNonAlpha = ! … ^[A-Za-z0-9 ]*$
6

You have to go through each character in the String and check Character.isDigit(char); or Character.isLetter(char);

Alternatively, you can use regex.

4 Comments

For example, "-1234" is a number, not an alphanumeric string. But your logic Character.isDigit will return false for "-". :(
I think it is Character.isLetter not Character.isletter
btw, since Java 1.0.2, we got the Character.isLetterOrDigit(char) method -- (since 1.5 the corresponding Character.isLetterOrDigit(int) one)
btw2, will fail the second example given in question (à is considered a letter by Character)
4

Use this function to check if a string is alphanumeric:

public boolean isAlphanumeric(String str)
{
    char[] charArray = str.toCharArray();
    for(char c:charArray)
    {
        if (!Character.isLetterOrDigit(c))
            return false;
    }
    return true;
}

It saves having to import external libraries and the code can easily be modified should you later wish to perform different validation checks on strings.

1 Comment

btw, will fail the second example given in question (à is considered a letter by Character)
2

If you can use the Apache Commons library, then Commons-Lang StringUtils has a method called isAlphanumeric() that does what you're looking for.

Comments

1

string.matches("^\\W*$"); should do what you want, but it does not include whitespace. string.matches("^(?:\\W|\\s)*$"); does match whitespace as well.

1 Comment

btw, will fail the second example given in question (à is considered a word character)
0

You can use isLetter(char c) static method of Character class in Java.lang .

public boolean isAlpha(String s) {
    char[] charArr = s.toCharArray();

    for(char c : charArr) {
        if(!Character.isLetter(c)) {
            return false;
        }
    }
    return true;
}

1 Comment

btw, will fail the second example given in question (à is considered a letter by Character)
0

Though it won't work for numbers, you can check if the lowercase and uppercase values are same or not, For non-alphabetic characters they will be same, You should check for number before this for better usability

Comments

0

I had to check a string contains at least 1 letter and 1 digit - my solution below

/**
 * <p>Checks if the String contains both letters and digits.</p>
 *
 * <p>{@code null} will return {@code false}.
 * An empty String str.isEmpty() will return {@code false}.</p>
 *
 * @param str the String to check, may be null
 * @return {@code true} if only contains letters and digits,
 * and is non-null or not empty
 */
public static boolean isAlphaAndNumeric(String str) {
    if (str == null || str.isEmpty()) {
        return false;
    }

    Pattern pattern = Pattern.compile("^[a-zA-Z0-9]*$");
    boolean containsSpecialChars = !pattern.matcher(str).matches();
    if (containsSpecialChars) {
        return false;
    }
    
    boolean containsLetter = false;
    boolean containsDigit = false;
    char[] chars = str.toCharArray();
    int i = 0;
    while (i < chars.length) {
        if (Character.isLetter(chars[i])) {
            containsLetter = true;
        }
        if (Character.isDigit(chars[i])) {
            containsDigit = true;
        }
        i++;
        if (containsDigit && containsLetter) {
            return true;
        }
    }
    return false;
}

1 Comment

not answering the question

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.