-1
Date,Location,Data1,Data2,Data3,$787 - $456 - $875,6.08 - 15.52,30.46,5,5,Name,LastName,42.71
Date,Location,Data1,Data2,Data3,$787 - $456 - $875,6.08 - 15.52 - 30.46,5,5,Name,LastName,42.71

Basically, how can I make the first line become like the second, using regex?

Is my logic right?: match 5 commas between the last $ sign and [a-z] and replace the second comma with " - "

Wiktor Stribiżew
  • 484,719
  • 26
  • 302
  • 397
Stakkr
  • 1

1 Answers1

2

It's probably easier (and more compatible with different languages) to use a positive lookahead to find the comma which is followed by 5 other commas and replace that with - using this regex:

,(?=(?:[^,]*,){5}[^,]*$)

In JavaScript you could do this:

let str = 'Date,Location,Data1,Data2,Data3,$787 - $456 - $875,6.08 - 15.52,30.46,5,5,Name,LastName,42.71';

str = str.replace(/,(?=(?:[^,]*,){5}[^,]*$)/, ' - ');
console.log(str);

In PHP:

$str = 'Date,Location,Data1,Data2,Data3,$787 - $456 - $875,6.08 - 15.52,30.46,5,5,Name,LastName,42.71';
$str = preg_replace('/,(?=(?:[^,]*,){5}[^,]*$)/', ' - ', $str);
echo $str;

Demo on 3v4l.org

In Python:

str = 'Date,Location,Data1,Data2,Data3,$787 - $456 - $875,6.08 - 15.52,30.46,5,5,Name,LastName,42.71';
str = re.sub(r',(?=(?:[^,]*,){5}[^,]*$)', ' - ', str);
print(str)

Demo on rextester

In all cases the output is:

Date,Location,Data1,Data2,Data3,$787 - $456 - $875,6.08 - 15.52 - 30.46,5,5,Name,LastName,42.71

Should your regex flavour not support lookaheads, you can replace that with a capturing group:

,(([^,]*,){5}[^,]*)$

and replace with

 - \1

Oracle demo on dbfiddle

Nick
  • 118,076
  • 20
  • 42
  • 73