java 使用正则表达式拆分简单的 JSON 结构

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13384454/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 12:31:31  来源:igfitidea点击:

Split a simple JSON structure using a regular expression

javaregexjsonsplit

提问by Rebeka

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:

我以前从未使用过正则表达式,我希望拆分具有一个或多个 JSON 对象的文件,JSON 对象不以逗号分隔。所以我需要在“}{”之间拆分它们并保留两个花括号。这是字符串的样子:

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

I would like a string array like using string.split()

我想要一个像使用的字符串数组 string.split()

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

回答by Denys Séguret

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

如果你的对象并不比你展示的更复杂,你可以使用这样的lookarounds

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

Exemple :

例子:

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);          
}

prints

印刷

{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.

如果您的对象更复杂,正则表达式可能不起作用,您将不得不解析您的字符串。