How to remove any non-alphanumeric characters?

java, regex

Solution

Use the not operator `^`:

[^a-zA-Z0-9.\-;]+

This means "match what is not these characters". So:

StringUtils.replacePattern(input, "[^a-zA-Z0-9.\\-;]+", "");

Don't forget to properly escape the characters that need escaping: you need to use two backslashes `\\` because your regex is a Java string.

Problem

I want to remove any non-alphanumeric character from a string, except for certain ones. `StringUtils.replacePattern(input, "\\p{Alnum}", "");` How can I also exclude those certain characters, like `.-;`?

Original source