Click here to Skip to main content
13,043,491 members (51,993 online)
Click here to Skip to main content
Add your own
alternative version


13 bookmarked
Posted 12 Feb 2015

Minimize Spacing using Regex

, 12 Feb 2015
Rate this:
Please Sign up or sign in to vote.
Regex patterns that will condense multiple spaces, tabs or line breaks into a single space, tab, or line break.


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 PatternReplace PatternDescription
[\t ]+
[ ]
Replaces groups of tabs or spaces with a single space.
([\t ])\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+

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


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


About the Author

Web Developer JBHworks
United States United States
No Biography provided

You may also be interested in...


Comments and Discussions

QuestionExcellent Article - Great Layout Pin
Kirk 1038982113-Feb-15 8:06
memberKirk 1038982113-Feb-15 8:06 
AnswerRe: Excellent Article - Great Layout Pin
FrostedSyntax13-Feb-15 8:19
memberFrostedSyntax13-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.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.170713.1 | Last Updated 12 Feb 2015
Article Copyright 2015 by FrostedSyntax
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid