Replace Multiple Spaces with One Space in a String

How do I replace multiple spaces with a single space in C#?

string sentence = "This is a sentence with multiple    spaces";
RegexOptions options = RegexOptions.None;
Regex regex = new Regex("[ ]{2,}", options);
sentence = regex.Replace(sentence, " ");

replace multiple spaces in a string with a single space

Your regex replaces any number of spaces (including zero) with a space. You should only replace two or more (after all, replacing a single space with itself is pointless):

$s = preg_replace("/ {2,}/", " ", $x);

Regex to replace multiple spaces with a single space

Given that you also want to cover tabs, newlines, etc, just replace \s\s+ with ' ':

string = string.replace(/\s\s+/g, ' ');

If you really want to cover only spaces (and thus not tabs, newlines, etc), do so:

string = string.replace(/  +/g, ' ');

How to replace multiple spaces with a single space using Bash?

Using tr:

$ echo "too         many       spaces." | tr -s ' '
too many spaces

man tr:

-s, --squeeze-repeats
replace each sequence of a repeated character that is listed in
the last specified SET, with a single occurrence of that charac‐
ter

Edit: Oh, by the way:

$ s="foo      bar"
$ echo $s
foo bar
$ echo "$s"
foo bar

Edit 2: On the performance:

$ shopt -s extglob
$ s=$(for i in {1..100} ; do echo -n "word " ; done) # 100 times: word word word...
$ time echo "${s//+([[:blank:]])/ }" > /dev/null

real 0m7.296s
user 0m7.292s
sys 0m0.000s
$ time echo "$s" | tr -s ' ' >/dev/null

real 0m0.002s
user 0m0.000s
sys 0m0.000s

Over 7 seconds?! How is that even possible. Well, this mini laptop is from 2014 but still. Then again:

$ time echo "${s//+( )/ }" > /dev/null

real 0m1.198s
user 0m1.192s
sys 0m0.000s

Substitute multiple whitespace with single whitespace in Python

A simple possibility (if you'd rather avoid REs) is

' '.join(mystring.split())

The split and join perform the task you're explicitly asking about -- plus, they also do the extra one that you don't talk about but is seen in your example, removing trailing spaces;-).

Regex to replace multiple spaces to single space excluding leading spaces

You can use a regex like this:

\b\s+\b

With a space _ substitution

Working demo

Sample Image

Update for IntelliJ: seems the lookarounds aren't working on IntelliJ, so you can try this other workaround:

(\w+ )\s+

With replacement string: $1

Working demo

Of course, above regex will narrow the scenarios but you can try with that.

Is there a simple way to remove multiple spaces in a string?

>>> import re
>>> re.sub(' +', ' ', 'The quick brown fox')
'The quick brown fox'


Related Topics



Leave a reply



Submit