我正在尝试用正则表达式替换以下模式:
"id": 1,"name": "A green door","price": 12.50,"tags": "green"
"id": 1,"name": "A green door","price": 12.50,"tags": "green"
"id": 1,"name": "A green door","price": 12.50,"tags": "green"
"id": 1,"name": "A green door","price": 12.50,"tags": "green"
我希望它输出以下内容:
1,"A green door",12.50,"green"
1,"A green door",12.50,"green"
1,"A green door",12.50,"green"
1,"A green door",12.50,"green"
然而,我希望表达式是一般的,因为值可能并不总是相同,唯一永远不会改变的是模式。但是我一直在尝试不同的表达方式:"(.*?)":
但是一直得到错误的结果。如果有人能帮助我,我会非常感激。
答案 0 :(得分:2)
这是一个非常简单的解决方案:
s/"[^"]*"\s*:\s*//g
如果你还想在字符串中允许反斜杠转义,我们可以更加花哨:
s/"(?:[^"\\]|\\.)*"\s*:\s*//g
答案 1 :(得分:1)
您可以使用 String#split
, Array#map
和 Array#join
方法完成此操作。
var str = `"id": 1,"name": "A green door","price": 12.50,"tags": "green"
"id": 1,"name": "A green door","price": 12.50,"tags": "green"
"id": 1,"name": "A green door","price": 12.50,"tags": "green"
"id": 1,"name": "A green door","price": 12.50,"tags": "green"`;
var res = str.split('\n').map(function(v) {
return v.split(',').map(function(v1) {
return v1.split(':')[1].trim();
}).join();
});
console.log(res);
或使用 String#replace
方法
var str = `"id": 1,"name": "A green door","price": 12.50,"tags": "green"
"id": 1,"name": "A green door","price": 12.50,"tags": "green"
"id": 1,"name": "A green door","price": 12.50,"tags": "green"
"id": 1,"name": "A green door","price": 12.50,"tags": "green"`;
var res = str.replace(/"\w+":\s*(?=.*?(?:[,|\n]|$))/g, '')
console.log(res);