Replace first instance of a character in a file name

I'm working on trying to clean up a bunch of music folders. Most are in the format "Artist Name - Album Title" but some are in the format "Artist_Name-Album_Title" and still others in "Artist_Name-Album_Title-Year" (or maybe other information in addition to or in place of Year. I'm trying to figure out how to create a rename preset that I can add to a button that will look for the first instance of a "-" and replace it with " - ". I've already got scripts to change the _ to spaces and to rename the folders to Artist Name\Album Title but the latter script presumes that the Artist Name and Album Title are separated by a " - ". I also need to be sure that only the first "-" is corrected because there are often multiple hyphens in the Album Title or information that follows. Hopefully that makes sense. Any help will be appreciated because, sadly, my brain just doesn't seem to want to wrap itself around how to compose a regular expression.

If you wanted the last - character, it's really easy:

Mode: Standard Wildcard Rename
Old name: *-*
New name: * - *

The problem is that the first * is eating as much of the name as it can (it is "greedy", in regular expression speak), so it's the last - that is being matched between the two *s.

We can use regular expressions to deal with that problem.

First, let's convert what we already have to an identical regular expression:

Mode: Regular Expressions
Old name: (.*)-(.*)
New name: \1 - \2

That does exactly the same thing as the first wildcard.

Since we're using regular expressions, let's improve it slightly so it only matches if there is at least one character on either side of the -, since the original versions will happily match zero characters and add spaces around a - at the very start or end of the name. This fixes that:

Mode: Regular Expressions
Old name: (.+)-(.+)
New name: \1 - \2

OK, now back to the original problem. You want to make the first (.+) not be "greedy"; that is, you want it to match as little of the name as possible before the -. You can do that by adding a ? after the .*, like this:

Mode: Regular Expressions
Old name: (.+?)-(.+)
New name: \1 - \2

And that should do what you need.

1 Like

That worked perfectly! Now I just have to spend some time playing with the examples that you provided so that I can try to figure out how to write my own regular expressions.

Thanks, Leo!