Cleanup Leading and Trailing Whitespaces

Here’s a regular expression to remove the leading and trailing whitespaces from a string:


$str =~ s/^s*//;    # remove leading whitespaces
$str =~ s/s*$//;    # remove trailing whitespaces

I have often seen this used to do the same thing:


$str =~ s/s*(.*?)s*$/$1/;

According to the book Mastering Regular Expressions by Jeffrey E.F. Friedl, this is slower. The reason he says is that “with each character, before allowing the dot to match, the ‘*?’ must try to see whether what follows can match. That’s a lot of backtracking, particularly since it’s the kind that goes in and out of the parenthesis.”

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.