Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / programming / string

Minimize Spacing using Regex

4.73/5 (12 votes)
12 Feb 2015CPOL 14K  
Regex patterns that will condense multiple spaces, tabs or line breaks into a single space, tab, or line break.

Introduction

For a full overview of RegEx visit this article.

There are several ways to use Regex to minimize spacing in a string and the way you choose will depend on what you desire for your end result.

The simplest pattern to do this would be to use "\s+" as your find pattern and "[ ]" as your replace pattern. This would replace any group of Unicode whitespace characters (including line breaks) with a single space.

If you want a more discerning approach, then try one of the following pattern combinations:

Find Pattern Replace Pattern Description
[\t ]+
[ ]
Replaces groups of tabs or spaces with a single space.
([\t ])\1+
$1
Uses a backreference to target groups of only tabs or only spaces. For example, if a group of spaces is followed by a group of tabs, it will keep one tab and one space.
([\t ]|(?:\r\n))\1+
$1

Same as above, except this pattern considers line breaks as well.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)