Saturday, January 18, 2025
HomeProgrammingHow to Remove Special Characters from String in Java

How to Remove Special Characters from String in Java

In Java, you can remove special characters from a string using regular expressions (regex). The most common approach is to use the replaceAll() method, which allows you to replace characters that match a given regular expression.

Here’s an example to remove all non-alphanumeric characters (i.e., special characters) from a string:

Example Code:

public class RemoveSpecialCharacters {
    public static void main(String[] args) {
        String input = "Hello, World! This is a test #123.";
        
        // Replace all characters that are not alphanumeric (a-z, A-Z, 0-9) or spaces
        String cleanedString = input.replaceAll("[^a-zA-Z0-9\\s]", "");
        
        System.out.println("Original String: " + input);
        System.out.println("Cleaned String: " + cleanedString);
    }
}

Explanation:

  • [^a-zA-Z0-9\\s]: This regular expression matches any character that is not (^) a letter (a-zA-Z), a number (0-9), or a space (\\s).
  • The replaceAll() method replaces all occurrences of these non-alphanumeric characters with an empty string (""), effectively removing them.
See also  What is an API (Application Programming Interface)?

Output:

Original String: Hello, World! This is a test #123.
Cleaned String: Hello World This is a test 123

This method can be adjusted if you want to allow additional characters (e.g., punctuation, underscores) by modifying the regular expression accordingly.

RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x