Use [^A-Za-z0-9].
Note: removed the space since that is not typically considered alphanumeric.
Answer from Mirek Pluta on Stack OverflowUse [^A-Za-z0-9].
Note: removed the space since that is not typically considered alphanumeric.
Try
return value.replaceAll("[^A-Za-z0-9]", "");
or
return value.replaceAll("[\\W]|_", "");
Trying to remove non-alphabetical characters from inputted string need help pls
How to remove non-alphanumeric characters in Java?
regex - Java remove all non alphanumeric character from beginning and end of string - Stack Overflow
regex - Java regular expression to remove all non alphanumeric characters EXCEPT spaces - Stack Overflow
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;}
Use ^ (matches at the beginning of the string) and $ (matches at the end) anchors:
s = s.replaceAll("^[^a-zA-Z0-9\\s]+|[^a-zA-Z0-9\\s]+$", "");
Use:
s.replaceAll("^[^\\p{L}^\\p{N}\\s%]+|[^\\p{L}^\\p{N}\\s%]+$", "")
Instead of:
s.replaceAll("^[^a-zA-Z0-9\\s]+|[^a-zA-Z0-9\\s]+$", "")
Where p{L} is any kind of letter from any language.
And p{N}is any kind of numeric character in any script.
For use in Latin-based scripts, when non-English languages are needed, like Spanish, for instance: éstas, apuntó; will in the latter become; stas and apunt. The former also works on non-Latin based languages.
For all Indo-European Languages, add p{Mn} for Arabic and Hebrew vowels:
s.replaceAll("^[^\\p{L}^\\p{N}^\\p{Mn}\\s%]+|[^\\p{L}^\\p{N}^\\p{Mn}\\s%]+$", "")
For Dravidian languages, the vowels may surround the consonant - as opposed to Semitic languages where they are "within" the character - like ಾ. For this use p{Me} instead. For all languages use:
s.replaceAll("^[^\\p{L}^\\p{N}^\\p{M}\\s%]+|[^\\p{L}^\\p{N}^\\p{M}\\s%]+$", "")
See regex tutorial for a list of Unicode categories
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.
You need to escape the \ so that the regular expression recognizes \s :
paragraphInformation = paragraphInformation.replaceAll("[^a-zA-Z0-9\\s]", "");