正则表达式匹配未加引号的字符串,但不匹配CSV中的数字

时间:2015-04-12 02:31:30

标签: javascript regex json

尝试为我的文本编辑器(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" ]

1 个答案:

答案 0 :(得分:1)

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

([\[,]\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)" ],'