如何在perl中查找字符串的最后一个索引

时间:2010-11-18 15:13:57

标签: perl

我是perl脚本编程的新手。有人可以告诉我如何找到字符串中的最后一个子字符串索引,该字符串在字符串中重复多次。

Actully我想从给定路径中提取文件名

 $outFile = "C:\\AOTITS\\BackOffice\\CSVFiles\\test.txt";

如果我能找到'\'的最后一个字符串,我会使用substr函数提取文件名。我已经通过以下方式做到了这一点。但它效率低下。

$fragment =  $outFile ;
$count = index($fragment, "\\");
while($count > -1) {
    $fragment =  substr ($fragment, index($fragment, '\\')+1);
    $count = index($fragment, '\\');
 }

有人可以告诉我一种有效的方法。

3 个答案:

答案 0 :(得分:14)

使用File::Basename

#!/usr/bin/env perl
use strict; use warnings;

use File::Basename;

my $outFile = "C:\\AOTITS\\BackOffice\\CSVFiles\\test.txt";

my ($name) = fileparse $outFile;
print $name, "\n";

注意:您也可以使用正则表达式执行此操作,但在处理文件名时,请使用专门用于处理文件名的函数。为了完整起见,下面是使用正则表达式捕获最后一部分的示例:

my ($name) = $outFile =~ m{\\(\w+\.\w{3})\z};

答案 1 :(得分:11)

关于标题中的问题,您可以使用rindex功能:

  
      
  • rindex STR,SUBSTR,POSITION
  •   
  • rindex STR,SUBSTR

         

    index类似,只是它返回STR中最后次出现的SUBSTR的位置。如果指定了POSITION,则返回   最后一次出现在该位置或之前开始。

  •   

也就是说,用File::Basename解析文件路径更好。

答案 2 :(得分:4)

  

有人能告诉我如何在字符串中找到s子串的最后一个索引,该字符串在字符串中重复多次?

my $whole = "Can someone tell me how to find the last index of s substring in a string which is repeated several times in the string?";
my $piece = "string";

my $place;
if ($whole =~ m { .* \Q$piece\E }gsx) {
    $place = pos($whole) - length($piece);
    print "Last found it at position $place\n";
} else {
    print "Couldn't find it\n";
}

但是接受思南的回答,因为他回答了你想知道的事情,而不是你所问的。 ☺