尝试为我的文本编辑器(BBEdit)写一个正则表达式来编码在几乎正确语法的JSON样式对象中尚未引用的字符串,以便可以在JavaScript上下文中使用,否则它们会将这些文本字符串视为未定义的变量。

因此:

[ 0, 0, Header, 1, 17, 480 ],
[ 1, 0, Start_track ],
[ 1, 0, Title_t, "Dance of the knights (Romeo & Juliet)" ],
[ 1, 0, Tempo, 600000 ],
[ 1, 0, Time_signature, 4, 2, 24, 8 ],
[ 1, 0, Key_signature, 1, "major" ]


会成为:

[ 0, 0, "Header", 1, 17, 480 ],
[ 1, 0, "Start_track" ],
[ 1, 0, "Title_t", "Dance of the knights (Romeo & Juliet)" ],
[ 1, 0, "Tempo", 600000 ],
[ 1, 0, "Time_signature", 4, 2, 24, 8 ],
[ 1, 0, "Key_signature", 1, "major" ]

最佳答案

您可以使用以下正则表达式。

([\[,]\s*)([A-Za-z_]\S*)(?=,|\s*\])


然后将匹配项替换为$1"$2"

DEMO

例:

> var s = '[ 1, 0, Title_t, "Dance of the knights (Romeo & Juliet)" ],';
> s.replace(/([\[,]\s*)([A-Za-z_]\S*)(?=,|\s*\])/g, '$1"$2"')
'[ 1, 0, "Title_t", "Dance of the knights (Romeo & Juliet)" ],'

09-07 17:26