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

时间:2015-10-11 11:55:31

标签: regex perl escaping substring indexof

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

Root\ToOrganization\Service_b37189b3-8505-4395_Out_BackOffice.xml

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

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

我正在尝试的代码:

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

我得到的输出:

-1

我该怎么办?

2 个答案:

答案 0 :(得分:5)

主要问题是你使用了无效的转义:

use warnings;
print "Root\ToOrganization\Service_b37189b3-8505-4395_Out_BackOffice.xml";
Unrecognized escape \T passed through at ... line 2.
Unrecognized escape \S passed through at ... line 2.
RootToOrganizationService_b37189b3-8505-4395_Out_BackOffice.xml

因此,您的$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";

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

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";

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

答案 1 :(得分:0)

双引号插入转义符\ T和\ S,因此您应该使用单引号' q // 进行测试。无论如何,从文件中读取(例如,使用<>)将对您有效,而无需对reindex相关代码进行任何更改,即这样可以正常工作:

warn rindex ($_, "\\") while (<>);
相关问题