Reputation: 918
I am searching for solution for some time that removes all special charachers is replace with "-".
Currently I am using replace() method.
for example like this to remove tab from string
str.Replace("\t","-");
Special characters:!@#$%^&*()}{|":?><[]\;'/.,~ and the rest
All I want is English alphabets, numbers[0-9], and "-"
Upvotes: 0
Views: 24147
Reputation: 127
Removes everything except letters, numbers and replaces with "-"
string mystring = "abcdef@_#124"
mystring = Regex.Replace(mystring, "[^\\w\\.]", "-");
Upvotes: 1
Reputation: 240
$(function () {
$("#Username").bind('paste', function () {
setTimeout(function () {
//get the value of the input text
var data = $('#Username').val();
//replace the special characters to ''
var dataFull = data.replace(/[^\w\s]/gi, '');
//set the new value of the input text without special characters
$('#Username').val(dataFull);
});
});
});
Upvotes: 0
Reputation:
LINQ version, if string is in UTF-8 (by default it is):
var newChars = myString.Select(ch =>
((ch >= 'a' && ch <= 'z')
|| (ch >= 'A' && ch <= 'Z')
|| (ch >= '0' && ch <= '9')
|| ch == '-') ? ch : '-')
.ToArray();
return new string(newChars);
Upvotes: 2
Reputation: 2532
Using regular expressions
The following example searches for the mentioned characters and replaces them with -
var pattern = new Regex("[:!@#$%^&*()}{|\":?><\[\]\\;'/.,~]");
pattern.Replace(myString, "-");
Using linq aggregate
char[] charsToReplace = new char[] { ':', '!', '@', '#', ... };
string replacedString = charsToReplace.Aggregate(stringToReplace, (ch1, ch2) => ch1.Replace(ch2, '-'));
Upvotes: 2
Reputation: 26896
You can use Regex.Replace method for it.
Pattern for "other than numbers,alphabet" could look like [^\w\d]
where \w
stands for any word character, \d
for any digit, ^
is negation and []
is character group.
See Regex language description for reference.
Upvotes: 4