I have some files with word characters and numbers at the end of filename. For some reason my regex is not working. Here are examples of my filenames:
test abc12345.zip
abcd def98765.zip
test xyz23456.zip
Here is my regex:
dir | rename-item -NewName {$_.name -replace "(\w\w\w\d\d\d\d\d.zip)","[$1].zip"}
When I run the selection snippet it removes:
abc12345
def98765
xyz23456
from the files names and just inserts the brackets:
test [].zip
abcd [].zip
test [].zip
How do I keep the contents within the brackets? Not sure why my code is removing everything in between the []
test [abc12345].zip
abcd [def98765].zip
test [xyz23456].zip
Replace the double quotes to single quotes. Powershell parses the content of double quotes and replaces your $1 with the content of the (non existent/empty) variable $1
Also, your regex can be made simpler to by using quantifiers for your word and digit characters so this
(\w\w\w\d\d\d\d\d.zip)
can be changed to this shorter version
(\w{3}\d{5}.zip)
Looking at your expected output, there's another problem with your current capturing group that is including the .zip extension. What you actually want instead of capturing everything including the extension
(\w{3}\d{5}.zip)
is to capture only the word/digit part
(\w{3}\d{5}).zip
Now you can use the capturing group to put brackets around them. Your final regex and replacement might then look like this
dir | rename-item -NewName {$_.name -replace '(\w{3}\d{5}).zip','[$1].zip'}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With