TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

<< Back to C-SHARP

C# Regex.Replace, Merge Multiple Spaces

Remove multiple spaces in strings with Regex.Replace. Handle other whitespace like newlines.
Regex.Replace, spaces. Regex.Replace can act upon spaces. It can merge multiple spaces in a string to one space. We use a pattern to change multiple spaces to single spaces. The characters \s+ come in handy.Regex.Replace
This program includes the System.Text.RegularExpressions namespace, which gives us easy access to Regex.Replace. In CollapseSpaces, we use the pattern "\s+" to indicate more than one whitespace.

And: This will match newlines, carriage returns, spaces and tabs. We then replace this pattern with a single space.

Result: You can see that the output values only have one space in between the words.

Note: Sometimes, after processing text with other regular expressions and methods, multiple spaces will appear.

Tip: CollapseSpaces() can solve that problem but results in even more complexity in the program.

C# program that uses Regex.Replace on spaces using System; using System.Text.RegularExpressions; class Program { static string CollapseSpaces(string value) { return Regex.Replace(value, @"\s+", " "); } static void Main() { string value = "Dot Net Perls"; Console.WriteLine(CollapseSpaces(value)); value = "Dot Net\r\nPerls"; Console.WriteLine(CollapseSpaces(value)); } } Output The Dev Codes The Dev Codes
Performance. If this method is in a hot path in your program, it would be better to replace it with a character-based implementation. It is possible to use a character array and then selectively write in characters, omitting unwanted ones.Char Array

Then: You can use the string constructor to convert the character array back to a string.

String Constructor
Summary. We saw a whitespace-processing method that uses the Regex.Replace method. I have used this method to process strings that were slightly invalid. It works well but increases overall complexity.RegexReplace
© TheDeveloperBlog.com
The Dev Codes

Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf