繁体   English   中英

perl substr获取子字符串

[英]perl substr to get a substring

#!/usr/bin/perl

my $str = "abc def yyy ghi";

print substr($str, 0 , index($str,' '));

我希望substr打印def yyy

print substr ($str, index ($str, ' '), rindex($str, ' ') does not work?

任何想法?

你没有完全指定你想要的逻辑,但最好的猜测是你想在第一个和最后一个空格之间打印字符。

您的示例代码将打印太多字符,因为它在最后一个空格之前打印#个字符(在您的示例中,10而不是7)。 要修复,您需要通过减去第一个空格前的字符数来调整打印的字符数。

此外,您需要在“索引”值的右侧开始一个字符以避免打印第一个空格 - 在下面的示例中为“+1”和“-1”

$cat d:\scripts\test1.pl
my $str = "abc def yyy ghi";

my $first_space_index = index ($str, ' ');
my $substring = substr($str, $first_space_index + 1, 
                             rindex($str, ' ') - $first_space_index - 1);
print "|$substring|\n";


test1.pl
|def yyy|

第三个参数是长度,而不是偏移量。 但是从字符串的末尾指示字符可能是否定的,这很容易从rindex和length获得,如下所示:

my $str = "abc def yyy ghi";
print substr( $str, 1 + index( $str, ' ' ), rindex( $str, ' ' ) - length($str) );

(注意添加1以获取第一个空格后的偏移量。)

如果要在第一个和最后一个空格之间打印文本,使用正则表达式会不会更容易?

print $1 if "abc def yyy ghi" =~ / (.*) /

坦率地说,substr / index / rindex真的不是去那里的方式。 你最好做以下事情:

my $str = "abc def yyy ghi";
my @row = split ' ', $str;
pop @row and shift @row;
print "@row";

哪个效率更低,但更好地捕捉实际意图

暂无
暂无

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

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