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 OverflowI am currently trying this two different ways and they aren't working - I'm checking the input value and running this every time a key is pressed:
input.replace(/[^a-zA-z]/, "");
and
for(var i = 0; i < input.length; i++){
if( input[i] == /[^a-zA-z]/g){
console.log("input " + input[i] + " is not a letter!");
input.replace(input[i], "");
}
}jsfiddle here
Replace [^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
Regular Expression: Any character that is not a letter or number
Replace all non alphanumeric characters, new lines, and multiple white space with one space
RegEx to remove all non alphanumeric characters
neovim - Regex for any character that is not alphanumeric, whitespace, or a doublequote - Vi and Vim Stack Exchange
To match anything other than letter or number you could try this:
[^a-zA-Z0-9]
And to replace:
var str = 'dfj,dsf7lfsd .sdklfj';
str = str.replace(/[^A-Za-z0-9]/g, ' ');
This regular expression matches anything that isn't a letter, digit, or an underscore (_) character.
\W
For example in JavaScript:
"(,,@,ยฃ,() asdf 345345".replace(/\W/g, ' '); // Output: " asdf 345345"
Be aware, that \W leaves the underscore. A short equivalent for [^a-zA-Z0-9] would be [\W_]
text.replace(/[\W_]+/g," ");
\W is the negation of shorthand \w for [A-Za-z0-9_] word characters (including the underscore)
Example at regex101.com
Jonny 5 beat me to it. I was going to suggest using the \W+ without the \s as in text.replace(/\W+/g, " "). This covers white space as well.