Search code examples
regexperlwhitespacetrim

Is there a Perl-compatible regular expression to trim whitespace from both sides of a string?


Is there a way to do this in one line?

$x =~ s/^\s+//;
$x =~ s/\s+$//;

In other words, remove all leading and trailing whitespace from a string.


Solution

  • $x =~ s/^\s+|\s+$//g;
    

    or

    s/^\s+//, s/\s+$// for $x;