在Perl中,s/^\s+//和s/\s+$//有什么区别?

9
我知道以下三行代码旨在将字符串提取到 $value 中,并将其存储在 $header 中。但是我不知道 $value =~ s/^\s+//;$value =~ s/\s+$//; 之间的区别。
$value =~ s/^\s+//;
$value =~ s/\s+$//;
$header[$i]= $value;

1
我知道以下三行代码旨在将字符串提取到$value中,并将其存储在$header中... 只是为了记录,它们并没有这样做。它们的目的是从标量$value两端删除空格,并将其放置在数组@header的第$i$个元素中。 - AmbroseChapel
3个回答

14

From perldoc perlfaq4:

How do I strip blank space from the beginning/end of a string?

A substitution can do this for you. For a single line, you want to replace all the leading or trailing whitespace with nothing. You can do that with a pair of substitutions:

s/^\s+//;
s/\s+$//;

You can also write that as a single substitution, although it turns out the combined statement is slower than the separate ones. That might not matter to you, though:

s/^\s+|\s+$//g;

In this regular expression, the alternation matches either at the beginning or the end of the string since the anchors have a lower precedence than the alternation. With the /g flag, the substitution makes all possible matches, so it gets both. Remember, the trailing newline matches the \s+, and the $ anchor can match to the absolute end of the string, so the newline disappears too.


以下内容来源于perldoc perlrequick:

To specify where it should match, we would use the anchor metacharacters ^ and $ . The anchor ^ means match at the beginning of the string and the anchor $ means match at the end of the string, or before a newline at the end of the string. Some examples:

"housekeeper" =~ /keeper/;         # matches
"housekeeper" =~ /^keeper/;        # doesn't match
"housekeeper" =~ /keeper$/;        # matches
"housekeeper\n" =~ /keeper$/;      # matches
"housekeeper" =~ /^housekeeper$/;  # matches

1

^ 表示以此字符串开始,$ 表示以此字符串结束。


你描述的是\z,而不是$$匹配字符串的结尾或者在字符串结尾前的换行符。 - ikegami

1

第一个只会替换行首的空格。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接