正则表达式如何在json表达式中获取组

时间:2014-02-01 00:50:24

标签: regex json

说我有以下JSON:

{"MyPerson":{"Firstname":"First","Lastname":"Last","Where":{"Street":"Street","Number":15}},"AnotherComplexObject":{"Another":"Yes","Me":"True"},"Count":1,"Start":2}

我删除了开始{并结束}并获取:

"MyPerson":{"Firstname":"First","Lastname":"Last","Where":{"Street":"Street","Number":15}},"AnotherComplexObject":{"Another":"Yes","Me":"True"},"Count":1,"Start":2

现在,我将使用什么正则表达式来获取“复杂对象”,例如在JSON中我想得到这两个结果:

{"Firstname":"First","Lastname":"Last","Where":{"Street":"Street","Number":15}}
{"Another":"Yes","Me":"True"}

我最接近解决方案的是这个正则表达式{[^}]*},但是该}结果无法选择"Number":15

1 个答案:

答案 0 :(得分:1)

# String
# "MyPerson":{"Firstname":"First","Lastname":"Last","Where":{"Street":"Street","Number":15}},"AnotherComplexObject":{"Another":"Yes","Me":"True"},"Count":1,"Start":2

/({[^}]+}})/
# http://rubular.com/r/rupVEn9yZo
# Match Groups
# 1. {"Firstname":"First","Lastname":"Last","Where":{"Street":"Street","Number":15}}

/({[^}]+})/
# http://rubular.com/r/H5FaoH18c8
# Match Groups
# Match 1
# 1. {"Firstname":"First","Lastname":"Last","Where":{"Street":"Street","Number":15}
# Match 2
# 1. {"Another":"Yes","Me":"True"}

/({[^}]+}})[^{]+({[^}]+})/
# http://rubular.com/r/zmcyjvoR1y
# Match Groups
# 1. {"Firstname":"First","Lastname":"Last","Where":{"Street":"Street","Number":15}}
# 2. {"Another":"Yes","Me":"True"}


# String
# {"MyPerson":{"Firstname":"First","Lastname":"Last","Where":{"Street":"Street","Number":15}},"AnotherComplexObject":{"Another":"Yes","Me":"True"},"Count":1,"Start":2}

/[^{]+({[^}]+}})[^{]+({[^}]+})/
# http://rubular.com/r/qCxN1Rk9Ka
# Match Groups
# 1. {"Firstname":"First","Lastname":"Last","Where":{"Street":"Street","Number":15}}
# 2. {"Another":"Yes","Me":"True"}