简体   繁体   English

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

[英]In Perl, what is the difference between s/^\s+// and s/\s+$//?

I know that the following three lines of codes aim to extract the string into $value and store it in $header. 我知道以下三行代码旨在将字符串提取为$ value并将其存储在$ header中。 But I do not know what are the differences between $value =~ s/^\\s+//; 但我不知道$value =~ s/^\\s+//;之间有什么区别$value =~ s/^\\s+//; and $value =~ s/\\s+$//; $value =~ s/\\s+$//; .

$value =~ s/^\s+//;
$value =~ s/\s+$//;
$header[$i]= $value;

From perldoc perlfaq4 : 来自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. 使用/g标志,替换将使所有可能的匹配,因此它获得两者。 Remember, the trailing newline matches the \\s+ , and the $ anchor can match to the absolute end of the string, so the newline disappears too. 请记住,尾随换行符匹配\\s+$ anchor可以匹配字符串的绝对结尾,因此换行符也会消失。


And from perldoc perlrequick : 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. anchor ^表示在字符串的开头匹配,而anchor $表示在字符串的结尾处匹配,或者在字符串结尾处的换行符之前。 Some examples: 一些例子:

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

^表示开头,$表示以此字符串结尾。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM