Click here to Skip to main content
15,867,756 members
Articles / General Programming / String
Tip/Trick

Minimize Spacing using Regex

Rate me:
Please Sign up or sign in to vote.
4.73/5 (12 votes)
12 Feb 2015CPOL 13.6K   13   2
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)


Written By
Web Developer JBHworks
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionExcellent Article - Great Layout Pin
Kirk 1038982113-Feb-15 8:06
Kirk 1038982113-Feb-15 8:06 
AnswerRe: Excellent Article - Great Layout Pin
FrostedSyntax13-Feb-15 8:19
FrostedSyntax13-Feb-15 8:19 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.