48

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?

1
  • You don't need regex if the name is the only data in the string. Otherwise you can probably use ( -|- | - ) Commented May 2, 2013 at 19:29

9 Answers 9

142

Instead of a RegEx use Replace for something that simple:

LastName = LastName.Replace(" ", String.Empty);
Sign up to request clarification or add additional context in comments.

6 Comments

This. I would vote this answer up right now, but I've reached my voting limit for today.
Didn't know there was a limit!
But not with tabs or other whitespace characters other than space (ordinal 32).
@maxwellb - From the OP, it looks like they are only dealing with "spaces"
Not sure what the deal was, I tried the above and it still didn't work, then I removed an earlier call to .Trim, then it started working. I guess it didnt like looking at the same thing twice. Either way, I am good to go now.
|
70

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.

1 Comment

This should be the correct answer to the original question.
14

No need for regex. This will also remove tabs, newlines etc

var newstr = String.Join("",str.Where(c=>!char.IsWhiteSpace(c)));

WhiteSpace chars : 0009 , 000a , 000b , 000c , 000d , 0020 , 0085 , 00a0 , 1680 , 180e , 2000 , 2001 , 2002 , 2003 , 2004 , 2005 , 2006 , 2007 , 2008 , 2009 , 200a , 2028 , 2029 , 202f , 205f , 3000.

3 Comments

Have a problem. Want to solve it with regex. Now I have two problems. Solve it with LINQ. Still two problems :-)
@JuliánUrbano Yes Regex can be a problematic while maintaining, but I can't say the same for Linq.
@JuliánUrbano, you should never want to solve anything because it is a particular API. Far too many questions are answered on this site with a LINQ answer, even though - in essence - it can be solved far more easily and far quicker. Pick the best solution.
3

Fastest and general way to do this (line terminators, tabs will be processed as well). Regex powerful facilities don't really needed to solve this problem, but Regex can decrease performance.

                       new string
                           (stringToRemoveWhiteSpaces
                                .Where
                                (
                                    c => !char.IsWhiteSpace(c)
                                )
                                .ToArray<char>()
                           )

OR

                       new string
                           (stringToReplaceWhiteSpacesWithSpace
                                .Select
                                (
                                    c => char.IsWhiteSpace(c) ? ' ' : c
                                )
                                .ToArray<char>()
                           )

4 Comments

FYI, I did a benchmark test between the first code snipped here (stringToRemoveWhiteSpaces) and the String.Join code posted by I4V and you new String(stringToRemoveWhiteSpaces...) code ran about 40% faster.
@JerrenSaunders But what about compared with the Regex solution? :-D
I can't say I tested the regex solution. I tend to agree with CSharpCoder's comments in this answer that the overhead of regex can sometimes be too much for the more simple task. That said, to be fair I should not make that assumption without including it in a benchmark.
The benchmark results when performing each operation 10M times: The first snippet here (.Where): 10813 ticks, I4V's Join/Where: 13140 ticks, dasblinkenlight's Regex.Replace: 22969 ticks, and Gabe's accepted answer's: 1297 ticks.
1

Using REGEX you can remove the spaces in a string.

The following namespace is mandatory.

using System.Text.RegularExpressions;

Syntax:

Regex.Replace(text, @"\s", "")

Comments

0

You can write so, for exaple with phone number:

private static string GetFormattedPhoneNumber(string phoneNumber)
    => string.IsNullOrEmpty(phoneNumber) ? string.Empty 
    : Regex.Replace(phoneNumber, @"[+,\-,\(,\), \s+]*", string.Empty);

static void Main(string[] args)
    {
       Console.WriteLine(GetFormattedPhoneNumber("+375 (24) 55-333 "));
    }
/*
    Output: 3752455333
*/

Comments

0

In my case, I have you remove whitespaces:

   var year = System.Text.RegularExpressions.Regex.Replace(space, @"&nbsp;", string.Empty).Replace("Year: ", string.Empty).Trim();

Comments

-2

Below is the code that would replace the white space from the file name into given URL and also we can remove the same by using string.empty instead of "~"

  if (!string.IsNullOrEmpty(url))
          {
           string origFileName = Path.GetFileName(url);
           string modiFileName = origFileName.Trim().Replace(" ", "~");
           url = url.Replace(origFileName , modiFileName );
          }
          return url;

1 Comment

Op said " I need to remove all whitespace" and used \s. But this handle only " " space and is mostly not related. While Trim() handles only leading and trailling space. I don't see fit.
-3

Why use Regex when you can simply use the Trim() method

Text='<%# Eval("FieldDescription").ToString().Trim() %>'

OR

string test = "Testing    ";
test.Trim();

1 Comment

He requires removing all spaces not just leading and ending spaces

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.