65.9K
CodeProject is changing. Read more.
Home

Minimize Spacing using Regex

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.73/5 (12 votes)

Feb 12, 2015

CPOL
viewsIcon

14033

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.