C# 从字符串中删除特定的特殊字符
我想使用正则表达式从字符串中删除空格(“”)、点(‘.)和连字符(-) 我目前的做法是:C# 从字符串中删除特定的特殊字符,c#,.net,regex,replace,C#,.net,Regex,Replace,我想使用正则表达式从字符串中删除空格(“”)、点(‘.)和连字符(-) 我目前的做法是: string input = "hello how --r dsbadb...dasjidhdsa.dasbhdgsa--dasb"; var res = input .ToCharArray() .Where(i => i != ' ' && i != '-' && i != '.') .Aggregate("
string input = "hello how --r dsbadb...dasjidhdsa.dasbhdgsa--dasb";
var res = input
.ToCharArray()
.Where(i => i != ' ' && i != '-' && i != '.')
.Aggregate(" ", (a, b) => a + b);
应该更容易阅读
var result = string.Concat(input.Where(c => !new[] { '.', ' ', '-' }.Contains(c)));
应该更容易阅读
var result = string.Concat(input.Where(c => !new[] { '.', ' ', '-' }.Contains(c)));
\s
将以空格为目标,\.
将以点为目标,-
将以连字符为目标,并将其替换为空字符串
\s
将以空格为目标,\.
将以点为目标,-
将以连字符为目标,并将其替换为空字符串尝试input=Regex.replace
。(等)-它将创建一个新字符串,而不是“就地”更改它。我建议您使用[.-]+
所以相邻字符会立即被替换。试试input=Regex.Replace
(etc)-它会创建一个新字符串,而不是“就地”更改它。我建议您使用[.-]+
,这样相邻字符会立即被替换。@Joey,为示例提供except。@Joey,with except输出将是helowrdsbajigvf
。测试您的代码。@Joey,提供带有except的示例。@Joey,带有except的输出将是helowrdsbajigvf
。测试你的代码。
string result = Regex.Replace(input, "[\s\.-]+", "");