1

I'm fairly new to regex, I can write expressions to do most simple file renaming jobs now but this one has me stuck.

I'm just trying to change the deliminator in a bunch of filenames from " -" to " - ", some examples:

"Author Name -Series 00 -Title.txt"  needs to become:
"Author Name - Series 00 - Title.txt"

"Author_Name -[Series 01] -Title -Genre.txt"  needs to become:
"Author_Name - [Series 01] - Title - Genre.txt"

The expression needs to be able to cope with 1, 2 or 3 " -" deliminators, and must ignore all other hyphens, for example "-" "- " and existing " - " should all be ignored. For example:

"File_Name1 - Sometext- more-info (V1.0).txt" Should not be changed at all.

It's for use in File Renamer, which is in Python.

Zarnia
  • 83
  • 5
  • 2
    [Replace `" -(?! )"g` with `" - "`](http://regex101.com/r/sB8rU3/1)? – Sam Oct 01 '14 at 21:28
  • That works. For some unknown reason in File Renamer it also adds an extra space to existing " - " but I can easily remove them so no bother. Thanks. – Zarnia Oct 02 '14 at 17:10

1 Answers1

0

You can use a positive look-ahead, search with the following pattern and replace it afterwards with the correct characters. There is a space in the beginning of the pattern. You can also use the white space selector \s.

 -(?=[^ ])

or with the whitespace character \s:

\s-(?=[^ ])

Here is an example to test the pattern in JavaScript:

// expected:

// "Author Name -Series 00 -Title.txt" ->
// "Author Name - Series 00 - Title.txt"

// "Author_Name -[Series 01] -Title -Genre.txt" ->
// "Author_Name - [Series 01] - Title - Genre.txt"

// "File_Name1 - Sometext- more-info (V1.0).txt" -> 
// no change

var regex = / -(?=[^ ])/g;
var texts = [
  "Author Name -Series 00 -Title.txt",
  "Author_Name -[Series 01] -Title -Genre.txt",
  "File_Name1 - Sometext- more-info (V1.0).txt"
];

for(var i = 0; i < texts.length; i++) {
  var text = texts[i];
  console.log(text, "->", text.replace(regex, ' - '));
}
Community
  • 1
  • 1
ssc-hrep3
  • 15,024
  • 7
  • 48
  • 87