Perl:查找char的最后一次出现"\"

Dav*_*ony 0 regex perl substring escaping indexof

我想从像这样的文件字符串中删除路径:

Root\ToOrganization\Service_b37189b3-8505-4395_Out_BackOffice.xml
Run Code Online (Sandbox Code Playgroud)

我试图找到最后一次出现的"\"的索引,所以我可以使用子串到那里.

但我不能在搜索中使用字符"\".我正在使用"\",但它不起作用......

我正在尝试的代码:

$file = "Root\ToOrganization\Service_b37189b3-8505-4395_Out_BackOffice.xml";
$tmp = rindex($file, "\\");
print $tmp;
Run Code Online (Sandbox Code Playgroud)

我得到的输出:

-1
Run Code Online (Sandbox Code Playgroud)

我能做什么?

mel*_*ene 5

主要问题是您使用无效转义:

use warnings;
print "Root\ToOrganization\Service_b37189b3-8505-4395_Out_BackOffice.xml";
Run Code Online (Sandbox Code Playgroud)
Unrecognized escape \T passed through at ... line 2.
Unrecognized escape \S passed through at ... line 2.
RootToOrganizationService_b37189b3-8505-4395_Out_BackOffice.xml
Run Code Online (Sandbox Code Playgroud)

所以你的$file变量不包含你的想法.

你的rindex电话本身很好,但你可以这样做(假设你在Windows系统上):

use strict;
use warnings;
use File::Basename;

my $path = "Root\\ToOrganization\\Service_b37189b3-8505-4395_Out_BackOffice.xml";
my $dir = dirname($path);
print "dir = $dir\n";
Run Code Online (Sandbox Code Playgroud)

或者(这适用于任何系统):

use strict;
use warnings;
use File::Spec::Win32;

my $path = "Root\\ToOrganization\\Service_b37189b3-8505-4395_Out_BackOffice.xml";
my $dir = (File::Spec::Win32->splitpath($path))[1];
print "dir = $dir\n";
Run Code Online (Sandbox Code Playgroud)

请注意,如果这实际上是一个真正的Windows路径,上面的代码将删除驱动器号(它是返回的列表的第一个元素splitpath).