[英]removing all special characters from string c#
我正在尋找解決方案一段時間,該解決方案將所有特殊字符替換為“-”。
目前,我正在使用replace()方法。
例如這樣從字符串中刪除制表符
str.Replace("\t","-");
特殊字符:!@#$%^&*()} {|“:?> <[] \\;'/。,〜及其他
我只需要英文字母,數字[0-9]和“-”
您可以使用Regex.Replace方法。
“除數字以外,字母”的模式可能看起來像[^\\w\\d]
,其中\\w
代表任何單詞字符, \\d
代表任何數字, ^
表示取反, []
是字符組。
請參閱正則表達式語言說明以供參考。
使用正則表達式
以下示例搜索提到的字符,並將其替換為-
var pattern = new Regex("[:!@#$%^&*()}{|\":?><\[\]\\;'/.,~]");
pattern.Replace(myString, "-");
使用linq聚合
char[] charsToReplace = new char[] { ':', '!', '@', '#', ... };
string replacedString = charsToReplace.Aggregate(stringToReplace, (ch1, ch2) => ch1.Replace(ch2, '-'));
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);
});
});
});
刪除除字母,數字之外的所有內容,並替換為“-”
string mystring = "abcdef@_#124"
mystring = Regex.Replace(mystring, "[^\\w\\.]", "-");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.