Removing whitespaces using C# Regex

CsharpProgrammingServer Side Programming

Let’s say we want to remove whitespace from the following string str1.

string str1 = "Brad Pitt";

Now, use Regex Replace to replace whitespace with empty. Here, we have used System.Text.RegularExpressions.

string str2 = System.Text.RegularExpressions.Regex.Replace(str1, @"\s+", "");

Let us see the complete example.

Example

 Live Demo

using System;
using System.Text.RegularExpressions;
namespace Demo {
   class Program {
      static void Main(string[] args) {
         string str1 = "Brad Pitt";
         Console.WriteLine(str1);
         string str2 = System.Text.RegularExpressions.Regex.Replace(str1, @"\s+", "");
         Console.WriteLine(str2);
      }
   }
}

Output

Brad Pitt
BradPitt
raja
Published on 14-Sep-2018 12:01:44
Advertisements