Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove all whitespace from C# string with regex

Tags:

string

c#

regex

I am building a string of last names separated by hyphens. Sometimes a whitespace gets caught in there. I need to remove all whitespace from end result.

Sample string to work on:

Anderson -Reed-Smith

It needs to end up as (no space after Anderson):

Anderson-Reed-Smith

The last name string is in a string variable, LastName.

I am using a regular expression:

Regex.Replace(LastName, @"[\s+]", ""); 

The result of this is:

Anderson -Reed-Smith.

I also tried:

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

and

Regex.Replace(LastName, @"\s", ""); 

What am I doing wrong?

like image 984
BattlFrog Avatar asked May 02 '13 19:05

BattlFrog


People also ask

How do I remove all spaces from a string?

Use the String. replace() method to remove all whitespace from a string, e.g. str. replace(/\s/g, '') . The replace() method will remove all whitespace characters by replacing them with an empty string.

How do I get rid of white space?

The replaceAll() method of the String class replaces each substring of this string that matches the given regular expression with the given replacement. You can remove white spaces from a string by replacing " " with "".

How do I remove all spaces from a string in C++?

The standard solution is to use the std::remove_if algorithm to remove whitespace characters from std::string using the Erase-remove idiom technique.

Which function is used to remove whitespace from the string?

The trim() function removes whitespace and other predefined characters from both sides of a string.


2 Answers

Instead of a RegEx use Replace for something that simple:

LastName = LastName.Replace(" ", String.Empty); 
like image 187
Gabe Avatar answered Oct 14 '22 02:10

Gabe


Regex.Replace does not modify its first argument (recall that strings are immutable in .NET) so the call

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

leaves the LastName string unchanged. You need to call it like this:

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

All three of your regular expressions would have worked. However, the first regex would remove all plus characters as well, which I imagine would be unintentional.

like image 33
Sergey Kalinichenko Avatar answered Oct 14 '22 00:10

Sergey Kalinichenko