Is there a Perl-compatible regular expression to t

2019-03-18 15:42发布

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 string.

12条回答
仙女界的扛把子
2楼-- · 2019-03-18 15:55
s/^\s*(\S*\S)\s*$/$1/
查看更多
Melony?
3楼-- · 2019-03-18 15:55
$var1 =~ s/(^\s*)(.*?)(\s*$)+/$2/;
查看更多
smile是对你的礼貌
4楼-- · 2019-03-18 15:57

Or this: s/\A\s*|\s*\Z//g

查看更多
老娘就宠你
5楼-- · 2019-03-18 15:59

$x =~ s/(^\s+)|(\s+$)//g;

查看更多
小情绪 Triste *
6楼-- · 2019-03-18 16:02

Funny you should bring this up!

I recently read an article analyzing the performance of twelve (!) different trim implementations.

Although the article specifically uses the JavaScript regex implementation, it uses Perl syntax, so I think it's apropos to this discussion.

查看更多
女痞
7楼-- · 2019-03-18 16:08

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.

查看更多
登录 后发表回答