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
I 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
Python regex to replace any characters that are not either letters or white space - Stack Overflow
neovim - Regex for any character that is not alphanumeric, whitespace, or a doublequote - Vi and Vim Stack Exchange
RegEx to remove all non alphanumeric characters
Regular Expression: Any character that is not a letter or number
So there are following things which are wrong in your pattern, let's address them first
A-z- It includes all the character from ascii table starting from A to z, which also has non alphabetical characters which we don't want to match, so the correct one should be[A-Z]if we want only uppercase, if we want both upper and lowercase then it should be[A-Za-z]or you can turn oniflag^\s-^means negation only when you use it as first character inside the character class elsewhere it is treated as literal^
So your regex should be
[^A-Za-z\s]
To match all non-word and non-whitespace characters, you can use [^\w\s] - \w is any letter, number, or underscore, and \s is whitespace. If you'd prefer to only get letters, you can use [^a-zA-Z\s] instead.
(Also, when you're negating a capture group, you only need to put ^ at the very start.)
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"