0
我必須規範化一個文件,刪除部分文本。 從文件中提取的樣本串如下:正則表達式匹配替換多次(javascript)
"a":{"$":"word"}, "b":{"$":"100"}, "c": {"$":"2017-02-08T16:20:36+13:00"}
目標應該是:
"a":"word","b":"100","c":"2017-02-08T16:20:36+13:00"
我確定了符合我的要求,正則表達式:
var regex = /{"\$":(.*)"}/g;
但是,當我做替換(在stackoverflow中找到類似的代碼):
let targetString = sourceString.replace(regex, "$1");
我有問題,只有第一個匹配被替換,並且「}」處理不當。
"a":"word"},"b":{"$":"100"},"c":{"$":"2017-02-08T16:20:36+13:00
下面的完整代碼和控制檯日誌:
let jsonC1 = `"a":{"$":"word"}, "b":{"$":"100"}, "c":{"$":"2017-02-08T16:20:36+13:00"}`;
//matches (regex) all white spaces and replace them with no space
let jsonN = jsonC1.replace(/\s/g,'');
console.log(`jsonN: ${jsonN}`);
var regex = /{"\$":(.*)"}/g;
let jsonS = jsonN.replace(regex, "$1");
console.log(`jsonS: ${jsonS}`);
jsonN: 「一」:{ 「$」: 「字」}, 「B」:{ 「$」:「100 「},」 C 「:{」 $ 「:」 2017-02-08T16:20:36 + 13:00 「}
jsonS: 」A「:」 字」 }, 「b」:{「$」:「100」},「c」:{「$」:「2017-02-08T16:20:36 + 13:00
使用這種乾杯,喬瓦尼
用'。*?'替換'。*'。 – Xufox
'... replace(/ \ {「\ $」:| \}/g,'')'應該完成這項工作。 – RobG
要麼'/ \ s * \ {「\ $」:(「[^」] *「)\}/g'或'/ \ s * \ {」\ $「:(」。*?「)\}/g' should do the trick。 – LukStorms