in reply to removing redundantwhitespace

$str =~ s/((^|\n| |\t)(?: |\t|(?<! |\t)\n)*)/$2/gs;

fixes most cases but doesn't convert a tab to a space if it is the first character in a white space string of characters.


Perl reduces RSI - it saves typing

Replies are listed 'Best First'.
Re^2: removing redundantwhitespace
by JadeNB (Chaplain) on Sep 13, 2008 at 21:33 UTC
    This doesn't collapse "a \nb" into "a\nb". It's difficult to tell from the desired output (because I can't see spaces at the ends of lines …), but it seems that the poster may have wanted that to happen.

      I thought I caught that case but, as you suggest, the white space on the end of the line is hard to see! The following simplifies the regex and fixes that case at the cost of complicating the substitution:

      $str =~ s/((^|\s)\s*)/length ($2) ? (-1 < index ($1, "\n") ? "\n" : ' +') : ''/ges;

      Oh, and it replaces tabs with spaces.


      Perl reduces RSI - it saves typing