使用正则表达式拆分简单的JSON结构 [英] Split a simple JSON structure using a regular expression

查看:653
本文介绍了使用正则表达式拆分简单的JSON结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我以前从未使用过正则表达式,并且正在寻找一个包含一个或多个JSON对象的文件,这些JSON对象之间没有逗号分隔.因此,我需要将它们在} {"之间分割,并保持两个大括号.字符串如下所示:

I've never used a regex before and I am looking to split up a file that has one or more JSON objects, the JSON objects are not separated by a comma. So I need to split them between "}{" and keep both curly braces. This is what the string looks like:

{id:"123",name:"myName"}{id:"456",name:"anotherName"}

我想要一个像使用string.split()

["{id:"123",name:"myName"}", "{"id:"456",name:"anotherName"}"]

推荐答案

如果您的对象不比您显示的对象复杂,则可以使用

If your objects aren't more complex than what you show, you may use lookarounds like this :

String[] strs = str.split("(?<=\\})(?=\\{)");

示例:

String str = "{id:\"123\",name:\"myName\"}{id:\"456\",name:\"yetanotherName\"}{id:\"456\",name:\"anotherName\"}";
String[] strs = str.split("(?<=\\})(?=\\{)");
for (String s : strs) {
    System.out.println(s);          
}

打印

{id:"123",name:"myName"}
{id:"456",name:"anotherName"}
{id:"456",name:"yetanotherName"}

如果您的对象更复杂,则正则表达式可能无法正常工作,您必须解析字符串.

If your objects are more complex, a regex wouldn't probably work and you would have to parse your string.

这篇关于使用正则表达式拆分简单的JSON结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆