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

nat*_*ath 7 perl

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

实际上我想从给定路径中提取文件名

 $outFile = "C:\\AOTITS\\BackOffice\\CSVFiles\\test.txt";
Run Code Online (Sandbox Code Playgroud)

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

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

有人可以告诉我一种方法,以有效的方式做到这一点.

Sin*_*nür 15

使用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";
Run Code Online (Sandbox Code Playgroud)

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

my ($name) = $outFile =~ m{\\(\w+\.\w{3})\z};
Run Code Online (Sandbox Code Playgroud)

  • @Sinan:是的,我一直[在正则表达式上表现出色](http://stackoverflow.com/questions/4213800/is-there-something-like-a-counter-variable-in-regular-expression-replace/ 4214173#4214173)最近.这是因为我正在更新即将发布的*Programming Perl*的第4版中的正则表达式章节,所以最近我都知道这一点. (2认同)

Eug*_*ash 11

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

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

    作品就像index除了它返回的位置最后 SUBSTR的STR发生.如果指定了POSITION,则返回从该位置开始或之前开始的最后一次出现.

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