使用RegEx与PowerShell匹配

时间:2015-11-01 03:55:36

标签: regex powershell

我有一个庞大的音乐库,我使用PowerShell / RegEx查找特定的歌曲。我很难找到我需要的确切艺术家。例如,此代码:

$artist = "Paul Young"
$allsongsRAW = Get-ChildItem -Path "C:\Music" -Recurse | Where-Object {$_.Extension -eq ".mp3"}
($allsongsRAW -match "(\s*$artist\s(-|\W)\s*)" | Sort-Object {Get-Random}).Name

返回:

Paul Young - Everything Must Change.mp3
Paul Young - Come Back And Stay.mp3
Paul Young - Everytime You Go Away.mp3
John Paul Young - Love Is In The Air.mp3
Paul Young - Wherever I Lay My Hat (That's My Home).mp3
Paul Young - What Becomes Of The Brokenhearted.mp3
Paul Young - Love of the Common People.mp3

这段代码:

$artist = "Queen"
$allsongsRAW = Get-ChildItem -Path "C:\Music" -Recurse | Where-Object {$_.Extension -eq ".mp3"}
($allsongsRAW -match "(\s*$artist\s(-|\W)\s*)" | Sort-Object {Get-Random}).Name

返回:

Storm Queen - Look Right Through (Jamie Jones Remix).mp3
Queen - The Invisible Man.mp3
Queen - Don't Stop Me Now.mp3
Storm Queen - Look Right Through (MK Dub III).mp3
Queen - Bohemian Rhapsody.mp3
Queen - I'm In Love With My Car.mp3
Queen - One Vision.mp3
Queen - A Kind Of Magic.mp3
Queen - Radio Ga Ga.mp3
Queen - Killer Queen.mp3
Queen - You're My Best Friend.mp3
Queen - Fat Bottomed Girls.mp3
Queen - Headlong.mp3
Queen - I Want It All.mp3
Queen - Somebody To Love.mp3
Queen - Bicycle Race.mp3
Queen - Crazy little thing called love.mp3
Queen - Body Language.mp3
Queen - Another One Bites The Dust.mp3
Queen - We Are The Champions.mp3
Queen - Tie Your Mother Down.mp3
Queen - Under Pressure.mp3
Queen - We Will Rock You.mp3
Queen - I Want To Break Free.mp3
Queen - Flash.mp3
Queen - Fight From The Inside.mp3

正如您所看到的,我正在使用的正则表达式正在挑选具有相似名称的其他艺术家,尤其是具有其他名称的艺术家继续执行搜索条件。

如何调整RegEx以仅显示我需要的艺术家?

1 个答案:

答案 0 :(得分:6)

使用克拉符号表示字符串的开头。

$allsongsRAW -match "^\s*$artist\s(-|\W)\s*"

我删除了你的外括号,因为它们似乎是无关紧要的。

此外,您可以将匹配移动到Where-Object条件:

Get-ChildItem -Path "C:\Music" -Recurse `
| Where-Object {($_.Extension -eq ".mp3") -and ($_.Name -match "^\s*$artist\s(-|\W)\s*")} `
| Sort-Object {Get-Random} `
| Select-Object -ExpandProperty Name;