PowerShell匹配字符串与Regex

时间:2014-10-20 13:14:05

标签: regex powershell

我正在编写一个脚本,将电视节目移动到我的驱动器上的相应文件夹中。我在将节目与其文件夹进行匹配时遇到问题。这是我遇到问题的代码片段:

#Remove all non-alphanumeric characters from the name
$newname = $Episode.Name -replace '[^0-9a-zA-Z ]', ' '  

#Split the name at S01E01 and store the showname in a variable (Text before S01E01) 
$ShowName = [regex]::Split($newname, 'S*(\d{1,2})(x|E)')[0]

#Match and get the destination folder where the names are similar
################## THIS IS WHERE THE ISSUE IS #######################
$DestDir = Gci -Path $DestinationRoot | Where { $ShowName -like "*$($_.Name)*" } | foreach {$_.Name }

例如,名为" Doctor Who 2005 S02E02 Tooth and Claw.mp4"没有返回一个名为" DoctorWho"的类似文件夹。

问题(S): 我可以修改$ DestDir以便我可以匹配名称?有没有更好的方法呢?

工作代码:

# Extract the name of the show (text before SxxExx)
$ShowName = [regex]::Split($Episode.Basename, '.(\d{1,3})(X|x|E|e)(\d{1,3})')[0]

# Assumption: There is a folder in TV shows directory that is named correctly, and the input file is named correctly
# Try to match by stripping all non-Alphabet characters from both names and check if the folder name contains the file name
$Folder = gci -Path $DestinationRoot | 
          Where {$_.PSisContainer -and `
          (($_.Name -replace '[^A-Za-z]','') -match ($ShowName -replace '[^A-Za-z]','')) } |
          select -ExpandProperty fullname

测试的一些示例输出:

Input file name:   Arrow S01E02.mp4
Show name:         Arrow 
Matching folder:   C:\Users\Public\Videos\TV Shows\Arrow
-----------------------------------------------------------------------
Input file name:   Big Bang Theory S3E03.avi
Show name:         Big Bang Theory 
Matching folder:   C:\Users\Public\Videos\TV Shows\The Big Bang Theory
-----------------------------------------------------------------------
Input file name:   Doctor Who S08E03.mp4
Show name:         Doctor Who 
Matching folder:   C:\Users\Public\Videos\TV Shows\Doctor Who (2005)
-----------------------------------------------------------------------
Input file name:   GameOfThronesS01E01.mp4
Show name:         GameOfThrones
Matching folder:   C:\Users\Public\Videos\TV Shows\Game Of Thrones
-----------------------------------------------------------------------

1 个答案:

答案 0 :(得分:2)

使用与您相同的方法根据您的建议确定节目名称的内容。使用Doctor Who 2005 S02E02 Tooth and Claw.mp4

$showName = $Episode -replace '[^0-9a-zA-Z ]'
$showName = ($showName -split ('S*(\d{1,2})(x|E)'))[0]
$showName = $showName -replace "\d"

我添加了一行$showName = $showName -replace "\d"来说明本赛季的一年。如果节目在其中间包含一个数字但是应该适用于大多数情况,则需要注意这一点。继续$DestDir决心。部分问题在于您向后进行Where比较。您想要查看节目名称是否是潜在文件夹的一部分,而不是相反。此外,由于潜在文件夹可能包含空格,因此comaparison也应包含该假设。

Get-ChildItem -Path $DestinationRoot -Directory  | Where-Object { ($_.name -replace " ") -like "*$($showName)*"}

我会继续使用Choice选项让用户确认该文件夹,因为它可能有多个匹配项。我想指出,可能很难考虑所有命名约定和差异,但你所拥有的是一个良好的开端。