in reply to Pulling white space off before/after string?

See perlfaq4: "How do I strip blank space from the beginning/end of a string?".

s/^\s+//; # strip white space from the beginning s/\s+$//; # strip white space from the end

Replies are listed 'Best First'.
Re^2: Pulling white space off before/after string?
by ecuguru (Monk) on Apr 17, 2007 at 04:58 UTC
    I just came back to post I found a working solution:
    $buff =~ s/ *$//; #Remove Trailing Spaces $buff =~ s/^ *//; #Remove Leading Spaces
    You've got the same idea I have, but I'm too regex newbie to figure out the differences. Can you tell me if there are any differences in our regexes?
    Thanks!!

      / *$/ means 'match zero or more space characters anchored to the end of the string', which will always match since it can always match zero characters. It will also match only space characters - other white space (such as tabs) will not match.

      /\s+$/ means 'match one or more white space characters anchored to the end of the string'. The \s includes spaces, tabs, and other forms of white space.

      See perlre for more information. The Tutorials section also has several entries in Pattern Matching, Regular Expressions, and Parsing, which you may find helpful.

      You are matching only space characters. bobf's version matches any white space characters (which includes spaces, tabs and various other characters including UNICODE white space characters).


      DWIM is Perl's answer to Gödel