in reply to Regular Expressions: Removing 'only' single spaces from a string

use warnings; use strict; my $str = "It is very very cold now"; $str =~ s/(?<! ) (?! )//g; print $str;

Prints Itisvery  verycoldnow which I doubt is what you want, but is what you asked for.


Perl is Huffman encoded by design.

Replies are listed 'Best First'.
Re^2: Regular Expressions: Removing 'only' single spaces from a string
by GrandFather (Saint) on Oct 20, 2005 at 18:30 UTC

    or you could use $str =~ s/\b \b//g;


    Perl is Huffman encoded by design.
      or you could use $str =~ s/\b \b//g;

      ...only if all the *non-space* characters are *word* characters:

      my $str = '@@@@ $$$ *** )))'; $str =~ s/\b \b//g; print $str;
      Thanks GrandFather. That almost worked 100%. I have some strings where the is no clear word boundary. Specifically, something like this:
      The boy to [ld his fat, her
      In that example, \b is failing to remove the space after to, and before '[', as well as the space after ',', and before her. Would I need to use \B as well?
        I found that the following works on both sample strings:
        $string =~ s/(\S)\s(\S)/$1$2/g;

        See Not_a_Number's reply here. Use the look behind/look ahead approach I suggested here instead.


        Perl is Huffman encoded by design.