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
regex - Java remove all non alphanumeric character from beginning and end of string - Stack Overflow
I know how to replace ALL non alphanumeric chars in a string but how to do it from just beginning and end of the string? I need this string: "theString," to be: theString replace ALL non More on stackoverflow.com
🌐 stackoverflow.com
Java Regex - Remove Non-Alphanumeric characters except line breaks - Stack Overflow
I'm trying to remove all the non-alphanumeric characters from a String in Java but keep the carriage returns. I have the following regular expression, but it keeps joining words before and after a line break. ... How would I be able to preserve the line breaks or convert them into spaces so that ... More on stackoverflow.com
🌐 stackoverflow.com
May 17, 2017
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
🌐
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).
🌐
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;
}

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