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
🌐
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 ... 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 ...
🌐
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
As I said, you can use the replaceAll() method of String along with regular expression to get rid of unwanted characters. You can define characters you want or remove in the regular expression as shown in our example.
🌐
Coderanch
coderanch.com › t › 406470 › java › Regex-replacing-special-characters
Regex for replacing special characters (Beginning Java forum at Coderanch)
March 19, 2007 - programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums · this forum made possible by our volunteer staff, including ... ... String name= "12E463~1.jpg"; String newName = name.replaceAll("[a-zA-Z1-90_\\- \\.]*","_"); String name has some value which contains some special characters.
Find elsewhere
🌐
GitHub
gist.github.com › rponte › 893494
Removing accents and special characters in Java: StringUtils.java and StringUtilsTest.java · GitHub
Removing accents and special characters in Java: StringUtils.java and StringUtilsTest.java · Raw · StringUtils.java · This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
🌐
Codementor
codementor.io › community › java regular expression: part 6 - replacing text
Java Regular Expression: part 6 - Replacing text | Codementor
April 5, 2019 - For instance, we need to replace error or redundant characters with the right ones. The java.lang.String class in Java supports 2 methods for these purposes: replace() and replaceAll() For instance, I have a string as follows:
🌐
Baeldung
baeldung.com › home › java › java string › java string.replaceall()
Java.String.replaceAll() | Baeldung
3 weeks ago - Many characters have special meanings in regex, for example: ... Sometimes, when we have these characters in our regex pattern, we want the regex engine to treat them as literal characters. We have two options to achieve that: escaping the character using backslash or putting it in a character class. Next, let’s solve the problem in a previous example: replacing all “.” characters with “:“: String input = "hi.java.hi.world"; String result = input.replaceAll("\\.", ":"); assertEquals("hi:java:hi:world", result); result = input.replaceAll("[.]", ":"); assertEquals("hi:java:hi:world", result);
🌐
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...
🌐
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,
🌐
Baeldung
baeldung.com › home › java › core java › guide to escaping characters in java regexps
Guide to Escaping Characters in Java RegExps | Baeldung
July 22, 2024 - We should note that Pattern.quote encloses the whole block with a single escape sequence. If we wanted to escape characters individually, we would need to use a token replacement algorithm. Let’s try to escape all special characters in a given string.
🌐
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]","");
🌐
YouTube
youtube.com › sdet- qa
Frequently Asked Java Program 24: How To Remove Junk or Special Characters in String - YouTube
Topic : How To Remove Junk or Special Characters in String #########################Udemy Courses: #########################Manual Testing+Agile with Jira To...
Published   October 18, 2019
Views   85K
🌐
Coderanch
coderanch.com › t › 454388 › java › replace-special-characters-string-java
replace special characters from string in the java (Servlets forum at Coderanch)
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums · this forum made possible by our volunteer staff, including ... ... hi i had a relative path ie D:/Working/geotrak/web/reports/SpeedReport.jasper"; in this relative path i want to replase the Backslash(/) by Forwordslash(\) Can any one say me how to do this in java Example: String str="/Working/geotrak/web/reports/SpeedReport.jasper"; String newStr = str.replace ('//' , '\\' ); System.out.println("old = " + str); System.out.println("new = " + newStr); But it not Replashing this / from \; no change happen so Help me to correct it Thank inn Advance
🌐
YouTube
youtube.com › shorts › gQT7BTWzw0A
Remove Special Characters from a String using Regular Expression in Java #shorts #javainterview - YouTube
Remove Special Characters from a String using Regular Expression in Java #shorts #javainterview
Published   March 20, 2023
🌐
DEV Community
dev.to › eyalk100 › the-complete-guide-to-java-string-replace-4jde
The Complete Guide to Java String Replace - DEV Community
March 1, 2021 - Just like in the StringBuilder ... replace all instances of the special character and it does mutate the original string buffer: Source String before replace : The world is schön. This is a String with special Character ö Using StringBuffer.replace() The world is schoen. This is a String with special Character ö String buffer after replace : The world is schoen. This is a String with special Character ö · The last method for replacing strings in Java that I’ll ...