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

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

    In zsh with PCRE mode active:

    function trim() {
        local out="$*"
        [[ "$out" =~ '^\s*(.*\S)\s*$' ]] && out="$match[1]" || out=''
        print -nr -- "$out"
    }
    

提交回复
热议问题