That depends on what you mean. If you just want to get rid of them, do this:
(Update: Apparently you want to keep digits as well, use the second lines in that case)

String alphaOnly = input.replaceAll("[^a-zA-Z]+","");
String alphaAndDigits = input.replaceAll("[^a-zA-Z0-9]+","");

or the equivalent:

String alphaOnly = input.replaceAll("[^\\p{Alpha}]+","");
String alphaAndDigits = input.replaceAll("[^\\p{Alpha}\\p{Digit}]+","");

(All of these can be significantly improved by precompiling the regex pattern and storing it in a constant)

Or, with Guava:

private static final CharMatcher ALNUM =
  CharMatcher.inRange('a', 'z').or(CharMatcher.inRange('A', 'Z'))
  .or(CharMatcher.inRange('0', '9')).precomputed();
// ...
String alphaAndDigits = ALNUM.retainFrom(input);

But if you want to turn accented characters into something sensible that's still ascii, look at these questions:

  • Converting Java String to ASCII
  • Java change áéőűú to aeouu
  • ń ǹ ň ñ ṅ ņ ṇ ṋ ṉ ̈ ɲ ƞ ᶇ ɳ ȵ --> n or Remove diacritical marks from unicode chars
Answer from Sean Patrick Floyd on Stack Overflow
🌐
Quora
quora.com › How-do-you-remove-special-and-space-characters-in-Java
How to remove special and space characters in Java - Quora
Answer: Java uses replaceAll() method. This method replaces each substring matching the given regular expression with the given replacement. A String strInput example shows this. Java uses String trim() method. This method removes leading and trailing whitespaces. This whitespace character unicod...
🌐
Quora
quora.com › How-do-you-remove-special-characters-from-a-string-in-Java-except-space
How to remove special characters from a string in Java except space - Quora
Answer: Java Strings are immutable, so you create a new string that contains only the characters you want to keep. Do this using a StringBuilder and iterating over the characters from the original string and use a condition to create a filter that decides if the character should be appended to th...
🌐
Blogger
javarevisited.blogspot.com › 2016 › 02 › how-to-remove-all-special-characters-of-String-in-java.html
How to remove all special characters from String in Java? Example Tutorial
Here is our sample Java program to demonstrate how you can use the replaceAll() method to remove all special characters from a String in Java.
Find elsewhere
🌐
Experts Exchange
experts-exchange.com › questions › 24425533 › Rereplace-remove-all-special-characters-except-space.html
Solved: Rereplace, remove all special characters except space | Experts Exchange
May 20, 2009 - I have descriptions of items that I need to remove ALL characters that are not letters or numbers, and I would like to preserve spaces. I am new to expressions and on overload since I cannot seem to come up with the magical solution... REReplace(str, "[^0-9a-zA-Z_]", "", "ALL") Any suggestions?
🌐
Stack Overflow
stackoverflow.com › questions › 51282917 › replace-all-special-character-except-and › 51283023
java - Replace all special character except "\" and "." - Stack Overflow
July 11, 2018 - String original="SOME TEXT"; String ... Character.isDigit(ch) || ch=='\\' || ch=='.'){ newStr+=ch; }else { newStr+=" "; } } ... String special = "&^#@$*" //what you think is special char....
🌐
Coderanch
coderanch.com › t › 406470 › java › Regex-replacing-special-characters
Regex for replacing special characters (Beginning Java forum at Coderanch)
March 19, 2007 - Originally posted by srikanth ramu: This will replace all the special characters except dot (.) String newName = name.replaceAll("[\\W]&&[^.]","_"); Thanks for replying. But I want all the characters apart from A-Z a-z 0-9 .
🌐
BeginnersBook
beginnersbook.com › 2024 › 06 › remove-special-characters-from-a-string-in-java
Remove special characters from a String in Java
June 1, 2024 - #Good -morning!"; //calling the user defined method for removing special chars String result = removeSpecialCharacters(input); System.out.println("Original: " + input); System.out.println("After removing special characters: " + result); } public static String removeSpecialCharacters(String str) { // This regular expression matches all special characters // [^a-zA-Z0-9\\s] matches any character that is not an // uppercase letter, lowercase letter, digit, or whitespace. String regex = "[^a-zA-Z0-9\\s]"; // Replace all special characters with an empty string // Note: There is no space between double quotes return str.replaceAll(regex, ""); } }
🌐
YouTube
youtube.com › watch
Remove special characters from string - YouTube
Hi Friends, #GainJavaKnowledgeWelcome to this channel Gain Java Knowledge. We are providing best content of Java in vide...
Published   July 16, 2022
Top answer
1 of 9
294

That depends on what you define as special characters, but try replaceAll(...):

String result = yourString.replaceAll("[-+.^:,]","");

Note that the ^ character must not be the first one in the list, since you'd then either have to escape it or it would mean "any but these characters".

Another note: the - character needs to be the first or last one on the list, otherwise you'd have to escape it or it would define a range ( e.g. :-, would mean "all characters in the range : to ,).

So, in order to keep consistency and not depend on character positioning, you might want to escape all those characters that have a special meaning in regular expressions (the following list is not complete, so be aware of other characters like (, {, $ etc.):

String result = yourString.replaceAll("[\\-\\+\\.\\^:,]","");


If you want to get rid of all punctuation and symbols, try this regex: \p{P}\p{S} (keep in mind that in Java strings you'd have to escape back slashes: "\\p{P}\\p{S}").

A third way could be something like this, if you can exactly define what should be left in your string:

String  result = yourString.replaceAll("[^\\w\\s]","");

This means: replace everything that is not a word character (a-z in any case, 0-9 or _) or whitespace.

Edit: please note that there are a couple of other patterns that might prove helpful. However, I can't explain them all, so have a look at the reference section of regular-expressions.info.

Here's less restrictive alternative to the "define allowed characters" approach, as suggested by Ray:

String  result = yourString.replaceAll("[^\\p{L}\\p{Z}]","");

The regex matches everything that is not a letter in any language and not a separator (whitespace, linebreak etc.). Note that you can't use [\P{L}\P{Z}] (upper case P means not having that property), since that would mean "everything that is not a letter or not whitespace", which almost matches everything, since letters are not whitespace and vice versa.

Additional information on Unicode

Some unicode characters seem to cause problems due to different possible ways to encode them (as a single code point or a combination of code points). Please refer to regular-expressions.info for more information.

2 of 9
72

This will replace all the characters except alphanumeric

replaceAll("[^A-Za-z0-9]","");
🌐
Javatpoint
javatpoint.com › how-to-remove-special-characters-from-string-in-java
How to Remove Special Characters from String in Java - Javatpoint
How to Remove Special Characters from String in Java with oops, string, exceptions, multithreading, collections, jdbc, rmi, fundamentals, programs, swing, javafx, io streams, networking, sockets, classes, objects etc,