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

前端 未结 13 960
醉话见心
醉话见心 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:32

    Arguing from the heretical, why do it at all? All of the above solutions are "correct" in that they trim whitespace from both sides of the string in one pass, but none are terribly readable (expect maybe this one). Unless the audience for your code is comprised of expert-level Perl coders each of the above candidates should have a comment describing what they do (probably a good idea anyway). By contrast, these two lines accomplish the same thing without using lookaheads, wildcards, midichlorines or anything that isn't immediately obvious to a programmer of moderate experience:

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

    There is (arguably) a performance hit, but as long as you aren't concerned with a few microseconds at execution the added readability will be worth it. IMHO.

提交回复
热议问题