
- C# Basic Tutorial
- C# - Home
- C# - Overview
- C# - Environment
- C# - Program Structure
- C# - Basic Syntax
- C# - Data Types
- C# - Type Conversion
- C# - Variables
- C# - Constants
- C# - Operators
- C# - Decision Making
- C# - Loops
- C# - Encapsulation
- C# - Methods
- C# - Nullables
- C# - Arrays
- C# - Strings
- C# - Structure
- C# - Enums
- C# - Classes
- C# - Inheritance
- C# - Polymorphism
- C# - Operator Overloading
- C# - Interfaces
- C# - Namespaces
- C# - Preprocessor Directives
- C# - Regular Expressions
- C# - Exception Handling
- C# - File I/O
- C# Advanced Tutorial
- C# - Attributes
- C# - Reflection
- C# - Properties
- C# - Indexers
- C# - Delegates
- C# - Events
- C# - Collections
- C# - Generics
- C# - Anonymous Methods
- C# - Unsafe Codes
- C# - Multithreading
- C# Useful Resources
- C# - Questions and Answers
- C# - Quick Guide
- C# - Useful Resources
- C# - Discussion
Removing whitespaces using C# Regex
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
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
- Related Articles
- Removing whitespaces using C# String.Empty
- Arranging lexicographically and removing whitespaces in JavaScript
- Whitespaces in Perl
- Remove the whitespaces from a string using replace() in JavaScript?
- Using regex in MongoDB findOne()
- Date format validation using C# Regex
- Date format validation using Java Regex
- Matching Nonprintable Characters using Java regex
- Removing the Links Default Underlines using CSS
- Removing punctuations from a string using JavaScript
- Remove all whitespaces from string - JavaScript
- Avoid MongoDB performance issues while using regex
- Removing Dotted Line around Active Links using CSS
- Removing the default underlines from links using CSS
- Removing all spaces from a string using JavaScript

Advertisements