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

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


Perl is Huffman encoded by design.
  • Comment on Re^2: Regular Expressions: Removing 'only' single spaces from a string
  • Download Code

Replies are listed 'Best First'.
Re^3: Regular Expressions: Removing 'only' single spaces from a string
by Not_a_Number (Prior) on Oct 20, 2005 at 18:48 UTC
    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;
Re^3: Regular Expressions: Removing 'only' single spaces from a string
by BioBoy (Novice) on Oct 20, 2005 at 18:46 UTC
    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;
        Won't work for a single space at the beginning or end of the string. To fix:
        $string =~ s/(\S|^)\s(\S|$)/$1$2/g;
        But the lookahead solution is preferable.

        Caution: Contents may have been coded under pressure.

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


      Perl is Huffman encoded by design.