【问题标题】:regex to remove paths from file names but only when path begins with a given pattern正则表达式从文件名中删除路径,但仅当路径以给定模式开头时
【发布时间】:2015-07-16 16:57:22
【问题描述】:

我有一个包含文件名的文件(除其他外)。只有部分文件名位于文件的行首:

~/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

谁能想出一个正则表达式来解决这个问题?

【问题讨论】:

  • 文件名是用空格分隔还是可以用管道符号等其他标记分隔?例如,管道两侧没有空格:/yet/another/path/pipeit.pl|tome.pl
  • @HåkonHægland 文件名总是用空格分隔

标签: regex perl


【解决方案1】:

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

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

【讨论】:

  • 为什么在否定字符类之后使用非贪婪量词?像[^\s]* 这样的否定字符类不会总是不贪婪吗?
  • 这只是我的一个习惯。任何带有*,+ 的东西都将永远是贪婪的。但是,您可以在类中包含其他可能位于下游的字符,这些字符充当限制器。这使您可以制作更健壮的最小表达式(尽管在这种情况下不是)。示例:(?:".*?"|'.*?'|[^>]*?)+
【解决方案2】:

试试这个:

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

Regex live here.

解释:

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

希望对你有帮助。


【讨论】:

    【解决方案3】:

    一个快速的,并不完美,但我认为它正在做需要做的事情 - 当然它可以被优化。

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-21
      • 1970-01-01
      • 2018-12-07
      • 2013-02-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多