lightswitchlover
lightswitchlover

Reputation: 135

Removing specific special characters from a string

I would like to remove spaces(' '), dots('.') and hyphens(-) from a string, using a regular expression.

My current approach:

string input = "hello     how --r dsbadb...dasjidhdsa.dasbhdgsa--dasb";          
var res = input
     .ToCharArray()
     .Where(i => i != ' ' && i != '-' && i != '.')
     .Aggregate(" ", (a, b) => a + b);

Upvotes: 1

Views: 306

Answers (3)

Ali Shah Ahmed
Ali Shah Ahmed

Reputation: 3333

string result = Regex.Replace(input, "[\s\.-]+", "");

\s would target space, \. would target dots, and - would target hyphens and will replace them with empty string

Upvotes: 0

Joey
Joey

Reputation: 354794

string filteredInput = Regex.Replace(input, "[ .-]+", "");

should be easier and more readable.

Upvotes: 7

Kirill Polishchuk
Kirill Polishchuk

Reputation: 56212

var result = string.Concat(input.Where(c => !new[] { '.', ' ', '-' }.Contains(c)));

Upvotes: 1

Related Questions