从String.split返回String包含部分匹配元素

时间:2010-09-13 05:55:40

标签: java

final String json = "\"name\" : \"john\" , \"worth\" : \"123,456\"";    
String[] ss = json.split("\"\\s*,\\s*\"");
System.out.println(json);
for (String s : ss) {
    System.out.println("--> " + s);
}

输出

"name" : "john" , "worth" : "123,456"
--> "name" : "john
--> worth" : "123,456"

我有什么方法可以获得

"name" : "john" , "worth" : "123,456"
--> "name" : "john"
--> "worth" : "123,456"

2 个答案:

答案 0 :(得分:2)

这有点像自己解析XML。你可以做到这一点,但为什么要这么做?有很多JSON parsers可用。使用其中一个来避免重新发明轮子。

答案 1 :(得分:2)

使用Regex

虽然我必须同意使用JSON解析器更有意义,即使你想使用正则表达式,String.split()也不是正确的工具。使用PatternMatcher

final String json = "\"name\" : \"john\" , \"worth\" : \"123,456\"";
final Pattern pattern =
    Pattern.compile("\"(.*?)\"\\s*:\\s*\"(.*?)\"", Pattern.DOTALL);
final Matcher matcher = pattern.matcher(json);
while(matcher.find()){
    System.out.println(matcher.group(1) + ":" + matcher.group(2));
}

输出:

name:john
worth:123,456

如果您确实想要检索引号,请将模式更改为

final Pattern pattern =
    Pattern.compile("(\".*?\")\\s*:\\s*(\".*?\")", Pattern.DOTALL);

输出:

"name":"john"
"worth":"123,456"

当然,这对于嵌套对象结构,数组,基元等不同的JSON结构无济于事。


使用JSON解析器

但是如果您的问题只是关于如何使用JSON解析器执行此操作,请使用JSONObject作为示例:

final String json = "{\"name\" : \"john\" , \"worth\" : \"123,456\"}";
final JSONObject jsonObject = new JSONObject(json);
@SuppressWarnings("unchecked")
final Iterator<String> it = jsonObject.keys();
while(it.hasNext()){
    final String nextKey = it.next();
    System.out.println(nextKey + ":" + jsonObject.getString(nextKey));
}

不需要课程。输出:

name:john
worth:123,456