正则表达式选择UNC中的最后一个文件夹

时间:2014-07-04 09:29:58

标签: regex powershell

我需要始终提取UNC路径的最后一个文件夹:

\\server\folder\subfolder (I want "subfolder")
\\server\folder\sub-folder (I want "sub-folder")
\\server\folder\subfolder$ (I want "subfolder$")
\\server\folder\sub folder (I want "sub folder")

我正在尝试使用正则表达式,但我无法找到解决方案。

谢谢!

3 个答案:

答案 0 :(得分:3)

使用.net可以避免正则表达式:

([system.io.directoryinfo]"\\server\folder\subfolder").BaseName

答案 1 :(得分:1)

你可以尝试这样的事情:'(?:.*?)\\([^\\]*)$'

示例:

@"
\\server\folder\subfolder (I want "subfolder")
\\server\folder\sub-folder (I want "sub-folder")
\\server\folder\subfolder$ (I want "subfolder$")
\\server\folder\sub folder (I want "sub folder")
"@ -split [environment]::NewLine | % { $_ -replace '(?:.*?)\\([^\\]*)$', '$1' }

subfolder (I want "subfolder")
sub-folder (I want "sub-folder")
subfolder$ (I want "subfolder$")
sub folder (I want "sub folder")

答案 2 :(得分:1)

使用此:

<强> INPUT.TXT

\\server\folder\subfolder
\\server\folder\sub-folder
\\server\folder\subfolder$
\\server\folder\sub folder

使用此Powershell

<强> test.ps1

$input_path = "input.txt"
$output_file = "output.txt"
$regex = "([^\\]+)$"
select-string -Path $input_path -Pattern $regex -AllMatches | % { $_.Matches } | % { $_.Value } > $output_file

<强> output.txt的

subfolder
sub-folder
subfolder$
sub folder