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

前端 未结 13 939
醉话见心
醉话见心 2021-02-08 07:45

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 stri

13条回答
  •  死守一世寂寞
    2021-02-08 08:18

    Tanktalus shows a benchmark for very small strings, but the problems get worse as the strings get bigger. In his code, I changed the top portion:

    my $a = 'a' x 1_000_000;
    
    my @x = (
      "   $a   ",
      "$a    ",
      $a,
      "    $a"
      );
    

    I get these results:

              Rate  single capture   trick  double
    single  2.09/s      --    -12%    -98%    -98%
    capture 2.37/s     13%      --    -98%    -98%
    trick   96.0/s   4491%   3948%      --     -0%
    double  96.4/s   4512%   3967%      0%      --
    

    As the string gets bigger, using "trick" and "double" are almost the same, and the common solution that most people go for, the "single" (including me, because I can't break that habit even though I know this), really starts to suck.

    Whenever you look at a benchmark, think about what it's telling you. To see if you understand it, change the data and try again. Make arrays long, scalars big, and so on. Make loops, greps, or regexes find stuff at the start, middle, and end. See if the new results match your prediction. Figure out what the trend is. Does performance get better and better, approach a limit, peak then start to decline, or something else?

提交回复
热议问题