Mariano L
Mariano L

Reputation: 1879

Add symbols to alphanumeric check with regex

I'm using this code to check if a String has non alphanumeric characters:

private boolean checkNonAlphanumeric(String text) {
    Pattern p = Pattern.compile("[^a-zA-Z0-9]");
    return p.matcher(text).find();
}

This works fine. But now I need to check this adding some symbols. In this case "-". What pattern should I use in this case?

ABCabc-ABC1234 = should be OK. a!#$%# = should be error.

Thanks!

Upvotes: 0

Views: 44

Answers (2)

Abdelhak
Abdelhak

Reputation: 8387

For only alphanumeric and the - use this:

private boolean checkNonAlphanumeric(String text) {
    Pattern p = Pattern.compile("[a-zA-Z0-9-]*");
    return p.matcher(text).find();
}

Upvotes: 1

Marco Altieri
Marco Altieri

Reputation: 3818

You can use:

private boolean checkNonAlphanumeric(String text) {
    Pattern p = Pattern.compile("[^a-zA-Z0-9\\-]");
    return p.matcher(text).find();
}

I would suggest to add the double slash just to be sure that if in the future you change the regular expression, the - will continue to be interpreted in the right way.

If you use only - and then you decide to add other characters before or after the -, it won't work. For example:

private boolean checkNonAlphanumeric(String text) {
    Pattern p = Pattern.compile("[^a-zA-Z0-9<->]");
    return p.matcher(text).find();
}

Will not match the -, but the following code will work:

private boolean checkNonAlphanumeric(String text) {
    Pattern p = Pattern.compile("[^a-zA-Z0-9<\\->]");
    return p.matcher(text).find();
}

Upvotes: 1

Related Questions