0

I've been trying to write a regex to match all the " - " deliminators in a filename except the first and last, so I can combine all the data in the middle into one group, for example a filename like:

Ann M Martin - Baby sitters Club - Baby sitters Little Sister - Super Special 04 - Karen, Hannie and Nancy - The Three Musketeers.doc

Has to become:

Ann M Martin - Baby sitters Club- Baby sitters Little Sister- Super Special 04- Karen, Hannie and Nancy - The Three Musketeers.doc

So basically I'm trying to replace " - " with "- " but not the first or last instance. The Filenames can have 1 to 6 " - " deliminators, but should only affect the ones with 3, 4, 5 or 6 " - " deliminators.

It's for use in File Renamer. flavor is JavaScript. Thanks.

Zarnia
  • 83
  • 5

3 Answers3

1

Can you not use a regex? If so:

var s = "Ann M Martin - Baby sitters Club - Baby sitters Little Sister - Super Special 04 - Karen, Hannie and Nancy - The Three Musketeers.doc";
var p = s.split(' - ');
var r = ''; // result output
var i = 0;
p.forEach(function(e){
  switch(i) {
    case 0: r += e; break;
    case 1: case p.length - 1: r += ' - ' + e; break;
    default: r += '- ' + e;
  }
  i++;
});
console.log(r);

http://jsfiddle.net/c7zcp8z6/1/

s=Ann M Martin - Baby sitters Club - Baby sitters Little Sister - Super Special 04 - Karen, Hannie and Nancy - The Three Musketeers.doc
r=Ann M Martin - Baby sitters Club- Baby sitters Little Sister- Super Special 04- Karen, Hannie and Nancy - The Three Musketeers.doc

This is assuming that the separator is always - (1 space, 1 dash, 1 space). If not, you need to split on - only, then trim each tokens before reconstructing.

sebnukem
  • 8,143
  • 6
  • 38
  • 48
0

Two options:

1 - You'll need to do some processing of your own by iterating through the matches using

( - )

and building a new string (see this post about getting match indices).

You'll have to check that the match count is greater than 2 and skip the first and last matches.

2 - Use

.+ - ((?:.+ - )+).+ - .+

to get the part of the string to be modified and then do a replace on the the dashes, then build your string (again using the indices from the above regex).

Community
  • 1
  • 1
adamdc78
  • 1,153
  • 8
  • 18
0

Thanks for the suggestions.

I got it to work this way

It replaces the first and last " - " with " ! ", so I can then do a simple Find and Replace of all remaining " - " with "- ", then change all the " ! " back to " - "

Zarnia
  • 83
  • 5