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

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

    I usually do it like this:

    ($foo) = $foo =~ /^\s*(.*?)\s*$/;
    

    Everything between the leading spaces and the trailing spaces is grouped and returned, so I can assign it to the same old variable.

提交回复
热议问题