7

I have a massive library of music, in which I am using PowerShell/RegEx to find particular songs. I am having trouble finding only the exact artist I need. For example, this code:

$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

Returns:

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

And this code:

$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

Returns:

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

As you can see, the Regular Expression I am using is picking up other Artists with a similar name, especially artists with other names proceeding the search criteria.

How can I tweak the RegEx to only display the artist I need?

1 Answer 1

12

Use the carat symbol to indicate the start of a string:

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

I eliminated the outer parentheses you had, because they appear to be extraneous.

Also, you can move the matching into the Where-Object condition:

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;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.