我想寫一個方法來提取Perl中前兩部分的windows路徑。Perl正則表達式提取windows路徑的前兩部分
例如, 'd:\ git_root_tfs \工作站\項目\相互作用\工具\服務器的規則檢查工具'
提取物爲: 'd:\ git_root_tfs \工作站'
sub Split_Location_as_VMPath {
my $location = shift;
# ^([d-z]:\\.+?\\.+?)\\
# ^(?:\\.*\\.*)\\
if($location ~~ m/^(?:\\.*\\.*)\\/){ # the path drive start from D to E;
# print "VMPath=$1\n";
# push @$vmPathList, $1;
return Convert_to_Lowercase($1);
}
return "Invalid Path $location";
}
如何編寫正則表達式?
測試用例:
{
my $item = Split_Location_as_VMPath('D:\VM\ia7-BGCDev8.1\test.vhd');
my $expected = Convert_to_Lowercase('D:\VM\ia7-BGCDev8.1');
ok($item eq $expected, "Test Split_Location_as_VMPath=$item");
$item = Split_Location_as_VMPath('E:\Hyper-V-2\ia-int-7.1Beta\test.vhd');
$expected = Convert_to_Lowercase('E:\Hyper-V-2\ia-int-7.1Beta');
ok($item eq $expected, "Test Split_Location_as_VMPath=$item");
$item = Split_Location_as_VMPath('D:\VM\ia7-int-7.1\test.vhd');
$expected = Convert_to_Lowercase('D:\VM\ia7-int-7.1');
ok($item eq $expected, "Test Split_Location_as_VMPath=$item");
$item = Split_Location_as_VMPath('D:\VM\ia7-int-8.1B153\test.vhd');
$expected = Convert_to_Lowercase('D:\VM\ia7-int-8.1B153');
ok($item eq $expected, "Test Split_Location_as_VMPath=$item");
$item = Split_Location_as_VMPath('D:\Hyper-v\IA5-SDE-WIN2K3(Feng Tong)\test.vhd');
$expected = Convert_to_Lowercase('D:\Hyper-v\IA5-SDE-WIN2K3(Feng Tong)');
ok($item eq $expected, "Test Split_Location_as_VMPath=$item");
$item = Split_Location_as_VMPath('D:\git_root_tfs\WorkStation\Projects\InterACT\Tools\server-rule-checker');
$expected = Convert_to_Lowercase('D:\git_root_tfs\WorkStation');
ok($item eq $expected, "Test Split_Location_as_VMPath=$item");
}