Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/perl/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
regex从文件名中删除路径,但仅当路径以给定模式开始时_Regex_Perl - Fatal编程技术网

regex从文件名中删除路径,但仅当路径以给定模式开始时

regex从文件名中删除路径,但仅当路径以给定模式开始时,regex,perl,Regex,Perl,我有一个包含文件名(以及其他内容)的文件。只有部分文件名位于文件行的开头: ~/remove/me/myexec.pl /some/other/path/exec.pl /yet/another/path/pipeit.pl | ~/remove/me/subdir/tome.pl ~/remove/me/deeply/nested/exec.pl 我想删除以~/remove/me开头的任何文件的文件路径。我还希望删除~/remove/me的任何子目录 这是我希望从上面得到的输出: myexe

我有一个包含文件名(以及其他内容)的文件。只有部分文件名位于文件行的开头:

~/remove/me/myexec.pl /some/other/path/exec.pl
/yet/another/path/pipeit.pl | ~/remove/me/subdir/tome.pl
~/remove/me/deeply/nested/exec.pl
我想删除以
~/remove/me
开头的任何文件的文件路径。我还希望删除
~/remove/me
的任何子目录

这是我希望从上面得到的输出:

myexec.pl /some/other/path/exec.pl
/yet/another/path/pipeit.pl | tome.pl
exec.pl
不以
~/remove/me
开头的文件路径必须保持独立

我能找到的最接近的方法是使用如下正则表达式:

s{~/remove/me/[^/]*?}{}gxms
但这并不能正确处理子目录,这给了我以下输出:

myexec.pl /some/other/path/exec.pl
/yet/another/path/pipeit.pl | subdir/tome.pl
deeply/nested/exec.pl
有人能想出一个正则表达式来解决这个问题吗?试试这个:

~\/remove\/me[^\s]*\/(?=[^\s]+)

解释:

 ~\/remove\/me            # starts with "~/remove/me"
 [^\s]*\/                 # match any non-space till last slash "/"
 (?=[^\s]+)               # match without taking the name and extension
希望能有帮助



另一种方式-
s{~/remove/me/(?:[^/\s]*?/)*}{}g

 ~/remove/me/
 (?:                           # Optional - Many non-spaced subdir's
      [^/\s]*? 
      /
 )*

一个快速的,不完美的,但我认为它做的是需要的-当然它可以优化

my $text = "~/remove/me/myexec.pl /some/other/path/exec.pl\n/yet/another/path/pipeit.pl | ~/remove/me/subdir/tome.pl\n~/remove/me/deeply/nested/exec.pl";

$text =~ s/~\/remove\/me[a-zA-Z0-9\/]*\/([a-zA-Z0-9.]+)/$1/g;
print $text;
结果如下:

myexec.pl /some/other/path/exec.pl
/yet/another/path/pipeit.pl | tome.pl
exec.pl

文件名是用空格分隔的,还是可以用管道符号等其他标记分隔?例如,管道两侧都没有空格:
/yet/other/path/pipeit.pl | tome.pl
@HåkonHægland文件名将始终用空格分隔为什么在否定字符类后使用非reedy量词?像
[^\s]*
这样的否定字符类不总是非reedy吗?这只是我的一个习惯。任何带有
*,+
的东西都是贪婪的。但是,您可以在类中包含其他字符,这些字符可能位于下游,充当限制器。这使您可以创建一个更健壮的最小表达式(但在本例中不是这样)。示例:
(?:“*?”|“.*?”|[^>]*?)+