Click here to Skip to main content
12,446,146 members (26,001 online)
Click here to Skip to main content
Add your own
alternative version

Stats

7.2K views
13 bookmarked
Posted

Minimize Spacing using Regex

, 12 Feb 2015 CPOL
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.

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)

Share

About the Author

FrostedSyntax
Web Developer JBHworks
United States United States
No Biography provided

You may also be interested in...

Pro
Pro

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.

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