Replace all special characters in a string with space in Java

In many real-world Java applications, you’ll receive strings that contain punctuation, symbols, or other non-alphanumeric “special” characters. Here, it’s important to clean up user input for search and normalize data. In this blog, we will learn how to clean this kind of data and replace it with spaces. You will learn here simply and easily.

Goal

Transform every character that is not a letter (A–Z or a–z) or digit (0–9) into a single space character.

Example

codeSpeedy#is@best!for-students –> codeSpeedy is best for students

Here, I remove all the special characters.

Code Snippets and Explanation

String input = "codeSpeedy#is@best!for-students";
String result = input.replaceAll("[^a-zA-Z0-9]", " ");       
  

output:
CodeSpeedy is best for students

  • [^a-zA-Z0-9] is a regular expression 
  • ^ inside [ ] means not.
  • This  a-zA-Z0-9 expression means it includes all lowercase letters, uppercase letters, and digits.
  • replaceAll( ) method replaces every such character with a space.
  • It matches exactly any character except letters or digits, spaces, punctuation, emoji, and currency symbols.
cleaned = res.replaceAll(" +", " ").trim();
  • Since consecutive special characters produce consecutive spaces.
  • This converts more spaces into exactly one space.
  • Trim ( ) removes the spaces in starting and ending of the string.

Whole code

public class SpecialCharReplacer {
    public static void main(String[] args) {
        String input = "codeSpeedy#is@best!for-students";
        String replace= input.replaceAll("[^a-zA-Z0-9]", " ");
        String result = replace.replaceAll(" +", " ").trim();
        System.out.println("Original: \"" + input + "\"");
        System.out.println("Cleaned : \"" + result + "\"");
    }
}

So the class [^a-zA-Z0-9] matches exactly any character except letters or digits—spaces, punctuation, emoji, currency symbols, even line breaks. By feeding this into replaceAll( ) , every “non-alphanumeric” character becomes a space.

Usecases

  • Data Cleaning
  • File Names
  • Database Storage
  • Text Processing
  • URL Slugs

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top