gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 05:55:52 26 4
gpt4 key购买 nike

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

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

最佳答案

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

关于regex - 在Perl中,s/^\s +//和s/\s + $//有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9262431/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com