Remove all whitespace from C# string with 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?

Answers


Instead of a RegEx use Replace for something that simple:

LastName = LastName.Replace(" ", String.Empty);

Need Your Help

How to publish ASP.NET 3.5 on IIS 5.1?

.net asp.net asp.net-3.5 publishing iis-5

I am using visual studio 2008 fo rasp .net 3.5 web development. I published the website and added virtual directory in IIS 5.1 built in windows xp.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.