Replacing all non-alphanumeric characters with empty strings Replacing all non-alphanumeric characters with empty strings java java

Replacing all non-alphanumeric characters with empty strings


Use [^A-Za-z0-9].

Note: removed the space since that is not typically considered alphanumeric.


Try

return value.replaceAll("[^A-Za-z0-9]", "");

or

return value.replaceAll("[\\W]|_", "");


You should be aware that [^a-zA-Z] will replace characters not being itself in the character range A-Z/a-z. That means special characters like é, ß etc. or cyrillic characters and such will be removed.

If the replacement of these characters is not wanted use pre-defined character classes instead:

 str.replaceAll("[^\\p{IsAlphabetic}\\p{IsDigit}]", "");

PS: \p{Alnum} does not achieve this effect, it acts the same as [A-Za-z0-9].