4b0
4b0

Reputation: 22323

Replace special character with white space through regex

I have a function which replace character.

public static string Replace(string value)
{
    value = Regex.Replace(value, "[\n\r\t]", " ");
    return value;
}


value="abc\nbcd abcd    abcd\ "

if in string there is any unwanted white space they are also remove.Means I want result like this
value="abcabcdabcd".
Help to change Regex Pattern to get desire result.Thanks a lot.

Upvotes: 1

Views: 4084

Answers (3)

jcollado
jcollado

Reputation: 40414

If you need to remove any number of whitespace characters from the string, probably you're looking for something like this:

value = Regex.Replace(value, @"\s+", "");

where \s matches any whitespace character and + means one or more times.

Upvotes: 1

grapeot
grapeot

Reputation: 1634

You may want to try \s indicating white spaces. With the statement Regex.Replace(value, @"\s", ""), the output will be "abcabcdabcd".

Upvotes: 0

Heinzi
Heinzi

Reputation: 172448

Instead of replacing your newline, tab, etc. characters with a space, just replace all whitespace with nothing:

public static string RemoveWhitespace(string value)
{
    return Regex.Replace(value, "\\s", "");
}

\s is a special character group that matches all whitespace characters. (The backslash is doubled because the backslash has a special meaning in C# strings as well.) The following MSDN link contains the exact definition of that character group:

Upvotes: 1

Related Questions