[英]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. 目前,我正在使用replace()方法。
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 "-" 我只需要英文字母,数字[0-9]和“-”
You can use Regex.Replace method for it. 您可以使用Regex.Replace方法。
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. “除数字以外,字母”的模式可能看起来像[^\\w\\d]
,其中\\w
代表任何单词字符, \\d
代表任何数字, ^
表示取反, []
是字符组。
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 使用linq聚合
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): LINQ版本,如果字符串为UTF-8(默认为):
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\\.]", "-");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.