You need to double-escape the \ character: "[^a-zA-Z0-9\\s]"

Java will interpret \s as a Java String escape character, which is indeed an invalid Java escape. By writing \\, you escape the \ character, essentially sending a single \ character to the regex. This \ then becomes part of the regex escape character \s.

Answer from jqno on Stack Overflow
Discussions

java - How to remove any non-alphanumeric characters? - Stack Overflow
I want to remove any non-alphanumeric character from a string, except for certain ones. StringUtils.replacePattern(input, "\\p{Alnum}", ""); How can I also exclude those certain characters, like .-;? ... This means "match what is not these characters". So: StringUtils.replacePattern(input, "[^a-zA-Z0-9.\\-;]+", ""); Don't forget to properly escape the characters that need escaping: you need to use two backslashes \\ because your regex is a Java ... More on stackoverflow.com
🌐 stackoverflow.com
February 24, 2015
java - Regex to remove all non-Alphanumeric characters with universal language support? - Stack Overflow
I would like to use Pattern's compile method to do this. Such as String text = "Where? What is that, an animal? No! It is a plane."; Pattern p = new Pattern("*some regex here*"); String delim = p. More on stackoverflow.com
🌐 stackoverflow.com
Trying to remove non-alphabetical characters from inputted string need help pls
The problem is that you're modifying the string while you're iterating over it. For example, if you have the input string 123, then on the first iteration i=0, so you'll remove the 1, resulting in the string 23. On the second iteration, i=1, and you'll remove the second character of the string which is 3. But you skipped the 2 because it was shifted backwards to an earlier index. You can hack around this, but it's simpler and more efficient to copy the input to a different variable and skip the non-alphabetical characters, instead of removing them in-place. More on reddit.com
🌐 r/learnprogramming
8
0
February 22, 2024
How to remove non-alphanumeric characters in Java?
Find answers to How to remove non-alphanumeric characters in Java? from the expert community at Experts Exchange More on experts-exchange.com
🌐 experts-exchange.com
September 16, 2022
🌐
GeeksforGeeks
geeksforgeeks.org › java › how-to-remove-all-non-alphanumeric-characters-from-a-string-in-java
How to remove all non-alphanumeric characters from a string in Java - GeeksforGeeks
July 15, 2025 - It can be punctuation characters ... dollar sign($), equal symbol(=), plus sign(+), apostrophes('). The approach is to use the String.replaceAll method to replace all the non-alphanumeric characters with an empty ...
🌐
CodingTechRoom
codingtechroom.com › question › java-remove-non-alphanumeric-characters-except-spaces
How to Use Java Regular Expressions to Remove Non-Alphanumeric Characters Except Spaces - CodingTechRoom
To create a Java regular expression that removes all non-alphanumeric characters while still keeping spaces, you can use the `replaceAll` method from the `String` class.
🌐
Interview Kickstart
interviewkickstart.com › home › blogs › learn › how to remove all non-alphanumeric characters from a string in java?
Remove Non-Alphanumeric Characters from a String in Java
December 19, 2024 - Learn how to remove all non-alphanumeric characters from a string in Java using regular expressions. Improve your Java programming skills now!
Find elsewhere
🌐
TutorialsPoint
tutorialspoint.com › article › remove-all-non-alphabetical-characters-of-a-string-in-java
Remove all non-alphabetical characters of a String in Java?
April 22, 2025 - The regular expression "\W+" matches all the non-alphabetical characters (punctuation marks, spaces, underscores, and special symbols) in a string. import java.util.Scanner; public class RemovingAlphabet { public static void main(String args[]) ...
🌐
GeeksforGeeks
geeksforgeeks.org › java › remove-all-non-alphabetical-characters-of-a-string-in-java
Remove all non-alphabetical characters of a String in Java - GeeksforGeeks
March 24, 2023 - It can be English alphabetic letters, blank spaces, exclamation points (!), commas (, ), question marks (?), periods (.), underscores (_), apostrophes ('), and at symbols (@). The approach is to use Java String.split method to split the String, ...
🌐
Alvin Alexander
alvinalexander.com › blog › post › java › remove-non-alphanumeric-characters-java-string
Java alphanumeric patterns: How to remove non-alphanumeric characters from a Java String | alvinalexander.com
April 18, 2019 - Here's a sample Java program that shows how you can remove all characters from a Java String other than the alphanumeric characters (i.e., a-Z and 0-9).
Top answer
1 of 2
4

The Java Pattern class, which is Java's implementation of regex, supports Unicode Categories, e.g. \p{Lu}. Since you want alphanumeric, that would be Categories L (Letter) and N (Number).

Since your example shows you also want to keep spaces, you need to include that. Let's use the Predefined Character Class \s, so you also get to keep newlines and tabs.

To find anything but the specified characters, use a Negation Character Class: [^abc]

All-in-all, that means [^\s\p{L}\p{N}]:

String output = input.replaceAll("[^\\s\\p{L}\\p{N}]+", "");
Where What is that an animal No It is a plane
Dónde Qué es eso un animal No Es un avión
Onde O que é isso um animal Não É um avião

Or see regex101.com for demo.


Of course, there are multiple ways to do it.

You could alternatively use the POSIX Character Class \p{Alnum}, and then enable UNICODE_CHARACTER_CLASS, using (?U).

String output = input.replaceAll("(?U)[^\\s\\p{Alnum}]+", "");
Where What is that an animal No It is a plane
Dónde Qué es eso un animal No Es un avión
Onde O que é isso um animal Não É um avião

Now, if you didn't want spaces, that could be simplified by using \P{xx} instead:

String output = input.replaceAll("(?U)\\P{Alnum}+", "");
WhereWhatisthatananimalNoItisaplane
DóndeQuéesesounanimalNoEsunavión
OndeOqueéissoumanimalNãoÉumavião
2 of 2
1

I am not an expert in all the languages of the world, however, your requirements could be met by doing this on a language specific basis:

Regex rgx = new Regex("[^a-zA-Z0-9 <put language specific characters to preserve here>]");
str = rgx.Replace(str, "");

I speak English and Korean, and can tell you that punctuation in Korean is identical to that used in English. As indicated above, you can add characters that should be preserved and not considered punctuation for a particular language. For example, let's say the tilde should not be considered punctuation. Then use the regex:

[^a-zA-Z0-9 ~]
🌐
Quora
quora.com › How-can-I-remove-all-non-alphanumeric-characters-from-a-string-in-Java
How to remove all non-alphanumeric characters from a string in Java - Quora
Answer: Here you go! Non-alphanumeric characters comprise of all the characters except alphabets and numbers. It can be punctuation characters like exclamation mark(!), at symbol(@), commas(, ), question mark(?), colon(:), dash(-) etc and special characters like dollar sign($), equal symbol(=), ...
🌐
w3resource
w3resource.com › java-exercises › re › java-re-exercise-21.php
Java - Remove all non-alphanumeric characters from a string
March 16, 2026 - public class test { public static void main(String[] args) { String text ="Java Exercises"; System.out.println("Original string: "+text); System.out.println("After removing all non-alphanumeric characters from the said string: "+validate(text)); text ="Ex@^%&%(ercis*&)&es"; System.out.println("\nOriginal string: "+text); System.out.println("After removing all non-alphanumeric characters from the said string: "+validate(text)); } public static String validate(String text) { return text.replaceAll("(?i)[^A-Z]", ""); } }
🌐
Java Code Geeks
javacodegeeks.com › home › core java
Remove Non-alphabetic Characters From String Array Example - Java Code Geeks
December 30, 2024 - Line 50: verifies that the white space, “!”, “~“, and digits are removed. Line 51: verifies that the “!” is removed. In this step, I will run the Junit tests and capture the test results. ... In this example, I created a simple maven project that included a Java class with four methods to remove non-alphabetic characters from a string.
🌐
Reddit
reddit.com › r/learnprogramming › trying to remove non-alphabetical characters from inputted string need help pls
r/learnprogramming on Reddit: Trying to remove non-alphabetical characters from inputted string need help pls
February 22, 2024 -

Hey guys! For class I'm trying to make a program to remove all non-alpha characters from a inputted string. Can you tell me why this isn't working?

For some reason when I input for example "testing test ! bla -o-" it outputs "testingtest!bla-o"

#include <iostream>
using namespace std;
int main() {

string inputStr;
getline(cin, inputStr);
for (int i = 0; i < inputStr.size(); i++){
if (!isalpha(inputStr[i])){
inputStr.replace(i, 1, "");
}
}
cout << inputStr;
return 0;
}

🌐
Experts Exchange
experts-exchange.com › questions › 29246681 › How-to-remove-non-alphanumeric-characters-in-Java.html
Solved: How to remove non-alphanumeric characters in Java? | Experts Exchange
September 16, 2022 - public String removeNonAlphanumericCharacters(String source) { return source.codePoints() .filter(Character::isLetterOrDigit) .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append) .toString(); } ... EARN REWARDS FOR ASKING, ANSWERING, AND MORE. Earn free swag for participating on the platform. ... Java is a platform-independent, object-oriented programming language and run-time environment, designed to have as few implementation dependencies as possible such that developers can write one set of code across all platforms using libraries.
🌐
GeeksforGeeks
geeksforgeeks.org › dsa › remove-characters-alphabets-string
Remove all characters other than alphabets from string - GeeksforGeeks
// Java program to remove all the characters // other than alphabets class GFG { // function to remove characters and // print new string static void removeSpecialCharacter(String s) { for (int i = 0; i < s.length(); i++) { // Finding the character whose // ASCII value fall under this // range if (s.charAt(i) < 'A' || s.charAt(i) > 'Z' && s.charAt(i) < 'a' || s.charAt(i) > 'z') { // erase function to erase // the character s = s.substring(0, i) + s.substring(i + 1); i--; } } System.out.print(s); } // Driver code public static void main(String[] args) { String s = "$Gee*k;s..fo, r'Ge^eks?"; removeSpecialCharacter(s); } } // This code is contributed by Rajput-Ji
Published   July 31, 2023
🌐
tutorialpedia
tutorialpedia.org › blog › how-to-remove-non-alphanumeric-characters
How to Remove Non-Alphanumeric Characters from a String (Preserving Spaces): Step-by-Step Function Guide — tutorialpedia.org
By preserving spaces, we ensure the output remains human-readable (e.g., "Hello World 123"). The core logic relies on regular expressions (regex) to identify and remove unwanted characters. Here’s how to build the function: Input: A string containing mixed characters (alphanumeric, non-alphanumeric, spaces).