AgainMe AgainMe - 2 months ago 8
C# Question

Remove white space from a string only if exceeds a certain size

I've this string:

Corso Vittorio Emanuele II 9 20122 Milano


this string was initially in this format:

Corso Vittorio Emanuele II 9
20122
Milano


so I removed the
NewLine
using a Regex expression:

var stringWithoutNewLine = Regex.Replace(text, "\t|\n|\r", string.Empty).Trim();


now I tried to remove the whitespace in this way:

return Regex.Replace(stringWithoutNewLine, @"\s+", string.Empty);


but it's not working as expected, 'cause I get this result:

CorsoVittorioEmanueleII920122Milano


when should be:

Corso Vittorio Emanuele II 9 20122 Milano

Answer

Change your regex from @"\s+" to @"\s{2,}". It will remove whitespaces that are repeated from 2 to (kind of) infinite number. Then, as Juharr noted, replace with a space:

Regex.Replace(yourString, @"\s{2,}", " ");
Comments