Javascript 用于分隔子集的正则表达式和嵌套方括号
我正在尝试构建一个快速JavaScript函数,该函数将接收如下JavaScript对象:Javascript 用于分隔子集的正则表达式和嵌套方括号,javascript,regex,json,square-bracket,Javascript,Regex,Json,Square Bracket,我正在尝试构建一个快速JavaScript函数,该函数将接收如下JavaScript对象: { "sample[one]": "value 1", "sample[hard][damn_you[0]]": "this 1", "sample[hard][damn_you[1]]": "this 2" } { "[sample][one]": "value 1", "[sample][hard][damn_you][0]": "this 1", "
{
"sample[one]": "value 1",
"sample[hard][damn_you[0]]": "this 1",
"sample[hard][damn_you[1]]": "this 2"
}
{
"[sample][one]": "value 1",
"[sample][hard][damn_you][0]": "this 1",
"[sample][hard][damn_you][1]": "this 2"
}
key = "["
+key.replace(/]/g,'[') // replace close brackets with open ones
// (to make them the same symbol)
.replace(/\[+$/,'') // trim off brackets at the end of the string
.replace(/\[+/g,"][") // replace brackets with "][" (separating the words)
+"]";
并将其转换为如下内容:
{
"sample[one]": "value 1",
"sample[hard][damn_you[0]]": "this 1",
"sample[hard][damn_you[1]]": "this 2"
}
{
"[sample][one]": "value 1",
"[sample][hard][damn_you][0]": "this 1",
"[sample][hard][damn_you][1]": "this 2"
}
key = "["
+key.replace(/]/g,'[') // replace close brackets with open ones
// (to make them the same symbol)
.replace(/\[+$/,'') // trim off brackets at the end of the string
.replace(/\[+/g,"][") // replace brackets with "][" (separating the words)
+"]";
细微但巨大的差别。我已经计算出了第一部分,其中包括将文本的第一部分用方括号括起来,但是当要取出嵌套的方括号并将其放出来时,我不知所措。我已经尝试了很长时间,但没有成功。以下是我目前掌握的情况:
var data = {
"sample[one]": "value 1",
"sample[hard][damn_you[0]]": "this 1",
"sample[hard][damn_you[1]]": "this 2"
},
subset = /^([a-z0-9-_]+?)\[/i;
for (var key in data) {
if (subset.test(key)) {
data[key.replace(subset,'[$1][')] = data[key];
} else {
data[key.replace(/^(.+)$/,'[$1]')] = data[key];
}
delete data[key];
}
哪个输出:
{
"[sample][one]": "value 1",
"[sample][hard][damn_you[0]]": "this 1",
"[sample][hard][damn_you[1]]": "this 2"
}
但在提取这些嵌套的方括号时,我不知所措。有什么想法吗?基本上,您正在查找不是方括号的每个连续字符集。括号的顺序不重要。所以你可以很容易地做这样的事情:
{
"sample[one]": "value 1",
"sample[hard][damn_you[0]]": "this 1",
"sample[hard][damn_you[1]]": "this 2"
}
{
"[sample][one]": "value 1",
"[sample][hard][damn_you][0]": "this 1",
"[sample][hard][damn_you][1]": "this 2"
}
key = "["
+key.replace(/]/g,'[') // replace close brackets with open ones
// (to make them the same symbol)
.replace(/\[+$/,'') // trim off brackets at the end of the string
.replace(/\[+/g,"][") // replace brackets with "][" (separating the words)
+"]";
例如,sample[hard][damn_you[0]]
执行以下步骤:
sample[hard][该死的你[0]
sample[hard[[该死的你[0[
sample[hard[[该死的你[0
[示例][硬][该死的你][0]