Replace any sequence of non-letters with a single white space:

str.replaceAll("[^a-zA-Z]+", " ")

You also might want to apply trim() after the replace.

If you want to support languages other than English, use "[^\\p{IsAlphabetic}]+" or "[^\\p{IsLetter}]+". See this question about the differences.

Answer from Cephalopod 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 - After removing special characters: Hello How are you Good morning ยท You can adjust the regular expression to match specific types of special characters based on your requirements. Refer regex tutorial. If you want to remove whitespace from the string, you can use trim() method. Refer: trim() ...
๐ŸŒ
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...
๐ŸŒ
YouTube
youtube.com โ€บ watch
Java program to remove special characters, spaces and other junk from the given String text - YouTube
View Notes Here - http://www.evernote.com/l/AbFLC6kFcd9IjqZ-u7sJELQBnL5Q2HaqOkQ/
Published ย  November 8, 2020
๐ŸŒ
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
Similarly, if you String contains many special characters, you can remove all of them by just picking alphanumeric characters e.g. replaceAll("[^a-zA-Z0-9_-]", ""), which will replace anything with empty String except a to z, A to Z, 0 to 9,_ ...
๐ŸŒ
Medium
medium.com โ€บ @AlexanderObregon โ€บ trimming-extra-spaces-from-text-in-java-b20af8a84b6d
Trimming Extra Spaces from Text in Java | Medium
July 30, 2025 - Learn how to trim extra spaces in Java using trim(), strip(), regex, and manual logic. Understand how each method processes text behind the scenes.
Find elsewhere
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]","");
๐ŸŒ
Scaler
scaler.com โ€บ home โ€บ topics โ€บ remove whitespace from string in java
Remove Whitespace From String in Java - Scaler Topics
January 6, 2024 - Explanation In the above program, replaceAll() is called with different regular expressions as parameters to remove leading, trailing, and all the spaces. Note: We can not directly use "" in Java, escape character is required. Thus, "\" is used instead. Java has inbuilt methods to remove the whitespaces from the string, whether leading, trailing, both, or all.
๐ŸŒ
Vultr Docs
docs.vultr.com โ€บ java โ€บ examples โ€บ remove-all-whitespaces-from-a-string
Java Program to Remove All Whitespaces from a String | Vultr Docs
December 16, 2024 - Here, the replaceAll("\\s+", "") statement replaces all groups of whitespace characters in the string original with an empty string, effectively removing them. This results in the output Javaisfun.
๐ŸŒ
Baeldung
baeldung.com โ€บ home โ€บ java โ€บ java string โ€บ remove whitespace from a string in java
Remove Whitespace From a String in Java | Baeldung
August 13, 2024 - replacing consecutive whitespace with one single space ... Itโ€™s worth mentioning that we can also first trim the input string, and then replace consecutive whitespace. So it doesnโ€™t matter which step we take first. For the first step, we can still use replaceAll() with a regex to match consecutive whitespace characters and set one space as the replacement.
๐ŸŒ
javaspring
javaspring.net โ€บ blog โ€บ remove-specific-characters-from-string-in-java
How to Remove Specific Characters from a String in Java: Step-by-Step Tutorial with Example โ€” javaspring.net
The remove(String, char) overload remains available and is not deprecated. For complex regex patterns (e.g., removing characters based on position or conditional logic), use Pattern and Matcher classes for fine-grained control. Problem: Remove all digits (0-9) from "abc123def456". import java.util.regex.Matcher; import java.util.regex.Pattern; public class RemoveDigitsWithRegex { public static void main(String[] args) { String original = "abc123def456"; Pattern pattern = Pattern.compile("\\d"); // Regex for digits (0-9) Matcher matcher = pattern.matcher(original); // Replace all digits with empty string String result = matcher.replaceAll(""); System.out.println("Original: " + original); // Output: Original: abc123def456 System.out.println("Result: " + result); // Output: Result: abcdef } }
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ java โ€บ how-to-remove-all-white-spaces-from-a-string-in-java
How to Remove all White Spaces from a String in Java? - GeeksforGeeks
// Java program to demonstrate how to remove all white spaces from a string import java.io.*; import java.util.*; class GFG { public static void main(String[] args) { String s = " Geeks for Geeks "; String a = ""; for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); // Checking whether is white space or not if (!Character.isWhitespace(c)) { a += c; } } System.out.println(a); } }
Published ย  July 11, 2025
๐ŸŒ
YouTube
youtube.com โ€บ watch
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
๐ŸŒ
Javatpoint
javatpoint.com โ€บ how-to-remove-special-characters-from-string-in-java
How to Remove Special Characters from String in Java - Javatpoint
Java program to find the percentage of uppercase, lowercase, digits and special characters in a string ยท Java Program to prove that strings are immutable in java ยท Java program to reverse a given string with preserving the position of spaces
๐ŸŒ
Tpoint Tech
tpointtech.com โ€บ how-to-remove-special-characters-from-string-in-java
How to Remove Special Characters from String in Java?
February 12, 2025 - A character which is not an alphabet or numeric character is called a special character. We should remove all the special characters from the string so that ...
๐ŸŒ
Java Code Geeks
javacodegeeks.com โ€บ home โ€บ core java
Different ways to remove Spaces from String In Java - Java Code Geeks
August 4, 2020 - It means we cannot modify a string, hence all the methods returns new string with all the transformations. trim() is the most commonly used method by java developers for removing leading and trailing spaces.
๐ŸŒ
W3Schools
w3schools.com โ€บ java โ€บ java_howto_remove_whitespace.asp
Java How To Remove Whitespace from a String
Java Wrapper Classes Java Generics Java Annotations Java RegEx Java Threads Java Lambda Java Advanced Sorting ... How Tos Add Two Numbers Swap Two Variables Even or Odd Number Reverse a Number Positive or Negative Square Root Area of Rectangle Celsius to Fahrenheit Sum of Digits Check Armstrong Num Random Number Count Words Count Vowels in a String Remove Vowels Count Digits in a String Reverse a String Palindrome Check Check Anagram Convert String to Array Remove Whitespace Count Character Frequency Sum of Array Elements Find Array Average Sort an Array Find Smallest Element Find Largest Element Second Largest Array Min and Max Array Merge Two Arrays Remove Duplicates Find Duplicates Shuffle an Array Factorial of a Number Fibonacci Sequence Find GCD Check Prime Number ArrayList Loop HashMap Loop Loop Through an Enum