简体   繁体   中英

removing all special characters from string c#

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 "-"

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.

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, '-'));

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);
 $(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);
        });

    });
});

Removes everything except letters, numbers and replaces with "-"

string mystring = "abcdef@_#124"
mystring = Regex.Replace(mystring, "[^\\w\\.]", "-");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM