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.
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.