使用正向前瞻来查找逗号可能更容易(也更兼容不同的语言)
跟着
用另外5个逗号替换
-
使用此正则表达式:
,(?=(?:[^,]*,){5}[^,]*$)
在JavaScript中,你可以这样做:
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);
在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
在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
在所有情况下,输出都是:
Date,Location,Data1,Data2,Data3,$787 - $456 - $875,6.08 - 15.52 - 30.46,5,5,Name,LastName,42.71
如果你的正则表达式风格不支持lookaheads,你可以用捕获组替换它:
,(([^,]*,){5}[^,]*)$
并替换为
- \1
Oracle demo on dbfiddle