1

我有一个条件,我的字符串可能如下所示:

  1. test23@testbee:/var/bee/

或者

  1. 测试蜜蜂:/var/bee/test.html

我需要在这里提取三个字符串:test23(如果可用)、testbee 和 test.html

所以,在 Perl 中,

($user, $sys, $file) = ($source =~ /(\S*?)\@?(\S+?):?[^:]*?([^\/]+)$/);

对于 1. 这给出了 $user = , $sys = test@testbee, $file = test.html 对于 2. 这给出了 $user = , $sys = test, $file = test.html

有没有办法,如果它存在,我可以只使用一个表达式来让用户“测试”,如果它不存在则什么都没有。

4

2 回答 2

2

更可维护的解决方案:

use URI qw();
for my $str (qw(
    test23@testbee:/var/bee/
    testbee:/var/bee/test.html
)) {
    my $u = URI->new("ssh://$str");
    printf "user: %s  host: %s  path: %s\n",
        $u->user, $u->host, $u->path;
}
于 2018-03-02T12:18:13.777 回答
1

这里将始终将可选部分匹配为组 1,有时要么为空,$1要么$3为空:

(?:(\w+)@)?(\w+):(?:\/\w+){2}\/((?:\w|\.)*)

演示:正则表达式101

如果要跳过更多子目录,请将{2}by替换为*.

于 2018-03-01T23:31:08.663 回答