Replace [^a-zA-Z0-9 -] with an empty string.
Regex rgx = new Regex("[^a-zA-Z0-9 -]");
str = rgx.Replace(str, "");
Answer from Amarghosh on Stack OverflowReplace [^a-zA-Z0-9 -] with an empty string.
Regex rgx = new Regex("[^a-zA-Z0-9 -]");
str = rgx.Replace(str, "");
I could have used RegEx, they can provide elegant solution but they can cause performane issues. Here is one solution
char[] arr = str.ToCharArray();
arr = Array.FindAll<char>(arr, (c => (char.IsLetterOrDigit(c)
|| char.IsWhiteSpace(c)
|| c == '-')));
str = new string(arr);
When using the compact framework (which doesn't have FindAll)
Replace FindAll with1
char[] arr = str.Where(c => (char.IsLetterOrDigit(c) ||
char.IsWhiteSpace(c) ||
c == '-')).ToArray();
str = new string(arr);
1 Comment by ShawnFeatherly
javascript - Remove not alphanumeric characters from string
Using regex to remove non-alphabetical characters in a string.
java - Regex to remove all non-Alphanumeric characters with universal language support? - Stack Overflow
Regex to remove all non alpha-numeric and replace spaces with +
Removing non-alphanumeric chars
The following is the/a correct regex to strip non-alphanumeric chars from an input string:
input.replace(/\W/g, '')
Note that \W is the equivalent of [^0-9a-zA-Z_] - it includes the underscore character. To also remove underscores use e.g.:
input.replace(/[^0-9a-z]/gi, '')
The input is malformed
Since the test string contains various escaped chars, which are not alphanumeric, it will remove them.
A backslash in the string needs escaping if it's to be taken literally:
"\\test\\red\\bob\\fred\\new".replace(/\W/g, '')
"testredbobfrednew" // output
Handling malformed strings
If you're not able to escape the input string correctly (why not?), or it's coming from some kind of untrusted/misconfigured source - you can do something like this:
JSON.stringify("\\test\red\bob\fred\new").replace(/\W/g, '')
"testredbobfrednew" // output
Note that the json representation of a string includes the quotes:
JSON.stringify("\\test\red\bob\fred\new")
""\\test\red\bob\fred\new""
But they are also removed by the replacement regex.
All of the current answers still have quirks, the best thing I could come up with was:
string.replace(/[^A-Za-z0-9]/g, '');
Here's an example that captures every key I could find on the keyboard:
var string = '123abcABC-_*(!@#$%^&*()_-={}[]:\"<>,.?/~`';
var stripped = string.replace(/[^A-Za-z0-9]/g, '');
console.log(stripped);
Outputs: '123abcABC'.
Hi, I am trying to remove non-alphabetical characters from the following string.
let string = "Anne, I vote more cars race Rome-to-Vienna"
I can get the result I am looking for with the following...
let newString = string.toLowerCase().split('').filter(el => el !== ' ' && el !== '-' && el !== ',').join('')
However I would prefer to use a much shorter piece of code using regex. I have gone over a few regex examples and tutorials but it still kind of confused me. Does anybody know the simplest way to remove the unwanted characters from the above string?
Thanks!!!
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
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 ~]
This is actually fairly straightforward.
Assuming str is the string you're cleaning up:
str = str.replace(/[^a-z0-9+]+/gi, '+');
The ^ means "anything not in this list of characters". The + after the [...] group means "one or more". /gi means "replace all of these that you find, without regard to case".
So any stretch of characters that are not letters, numbers, or '+' will be converted into a single '+'.
To remove parenthesized substrings (as requested in the comments), do this replacement first:
str = str.replace(/\(.+?\)/g, '');
function replacer() {
var str = document.getElementById('before').value.
replace(/\(.+?\)/g, '').
replace(/[^a-z0-9+]+/gi, '+');
document.getElementById('after').value = str;
}
document.getElementById('replacem').onclick = replacer;
<p>Before:
<input id="before" value="Durarara!!x2 Ten" />
</p>
<p>
<input type="button" value="replace" id="replacem" />
</p>
<p>After:
<input id="after" value="" readonly />
</p>
str = str.replace(/\s+/g, '+');
str = str.replace(/[^a-zA-Z0-9+]/g, "");
- First line replaces all the spaces with + symbol
- Second line removes all the non-alphanumeric and non '+' symbols.