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

Probably not very efficient, but the best I can come up with at short notice:

$str =~ s/(\S) (\S)/$1$2/g;

Update:See Roy Johnson's comment above on Trix606's similar snippet. Code fixed for single spaces at start and end of string:

s/(\S|^) (\S|$)/$1$2/g;

Replies are listed 'Best First'.
Re^2: Regular Expressions: Removing 'only' single spaces from a string
by BioBoy (Novice) on Oct 20, 2005 at 23:25 UTC
    what does the $1$2 mean? Doesn't the $ regular expression designate the end of the string?

      In the regular expression, yes it does. In the replacement expression $n is the n'th capture string in the regular expression. So for s/(x) (y)/$1$2)/ 'x y' gets replaced with 'xy' for example.


      Perl is Huffman encoded by design.