kitokid
kitokid

Reputation: 3117

Limit special characters with Regex

I want my regex to match any string with "special" characters other than . and /. The other special characters are on a sort of blacklist. However, at runtime, I get an Illegal repetition error. How can I resolve that?

Pattern regex = Pattern.compile("!@#$%^&*()-_+=|\\}]{[\"':;?><,");
Matcher matcher = regex.matcher(key);
if (matcher.find()) {
    return false;
}

Upvotes: 0

Views: 1249

Answers (1)

Mikhail Vladimirov
Mikhail Vladimirov

Reputation: 13890

Probably it would be better to just specify what is allowed instead of what is denied:

Pattern regex = Pattern.compile ("^[\\w\\s\\./]*$");
if (!regex.matcher(key).matches ()) return false;

This allows only letters, digits, whitespace, dot ('.') and slash ('/').

Upvotes: 1

Related Questions