【问题标题】:Perl: find the last occurrence of the char "\"Perl:查找字符“\”的最后一次出现
【发布时间】:2016-01-08 23:04:46
【问题描述】:

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

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

我能做什么?

【问题讨论】:

  • 缺少use strict; use warnings;
  • 提示:rindex 调用中有双反斜杠,但路径中只有一个反斜杠。为什么?
  • @melpomene ,该行将通过读取文本文件来,这是我从测试文件行中获取的格式...
  • 不,不是。对于来自文本文件的行,您的代码可以正常工作。

标签: regex perl escaping substring indexof


【解决方案1】:

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

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 返回的列表的第一个元素)。

【讨论】:

  • 这是一个很好的答案,唯一的问题是你的代码返回了文件名,我需要没有文件名的目录结构:)
  • @DavidGidony 已更新。
【解决方案2】:

双引号内插转义\T和\S,所以你应该使用单引号'q//来测试。无论如何,从文件中读取(例如,使用 )将为您工作,而无需对与重新索引相关的代码进行任何更改,即这工作正常:

warn rindex ($_, "\\") while (<>);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-31
    • 2011-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-03
    • 1970-01-01
    相关资源
    最近更新 更多