如何在java中使用正则表达式获取所有匹配项

时间:2015-11-09 11:44:49

标签: java regex

我试图获取与我给定的正则表达式匹配的所有可能值。我有这个长字符串,包括表的架构。我需要获取表的所有字段名称。我尝试使用正则表达式和while循环迭代匹配器。我可以在第一次迭代中从group(1)获取第一个列值,但之后我得到null。

String pattern = "\\},\"|\":\\{\"([^\"]+)\":\\{\"";
String schema = "{\"columns\":{\"scenario\":{\"type\":\"STRING\",\"isScoreParam\":false,\"isIndex\":false},\"_duration_1\":{\"type\":\"STRING\",\"isScoreParam\":false,\"isIndex\":true},\"query\":{\"type\":\"STRING\",\"isScoreParam\":false,\"isIndex\":false}},\"primaryKeys\":[]}";    
Matcher m = Pattern.compile(pattern).matcher(schema);

while (m.find()) {
            System.out.println("Found value: " + m.group(0) );
            System.out.println("Found value: " + m.group(1));
}

上述代码的输出是,

Found value: ":{"scenario":{"
Found value: scenario
Found value: },"
Found value: null
Found value: },"
Found value: null
Found value: },"
Found value: null

我需要过滤掉场景,_duration_1,从上面的字符串中查询并将其插入到数组中。但我还不清楚该怎么做。我不确定是否可以用正则表达式来做到这一点。所以,有人可以请你帮忙。在此先感谢... !!

更新1

我用以下代码尝试了json解析器,

JSONObject json = (JSONObject)new JSONParser().parse("{\"columns\":{\"scenario\":{\"type\":\"STRING\",\"isScoreParam\":false,\"isIndex\":false},\"_duration_1\":{\"type\":\"STRING\",\"isScoreParam\":false,\"isIndex\":true},\"query\":{\"type\":\"STRING\",\"isScoreParam\":false,\"isIndex\":false}},\"primaryKeys\":[]}");

System.out.println(json.get("columns"));

然后你得到输出,

{"_duration_1":{"isIndex":true,"isScoreParam":false,"type":"STRING"},"scenario":{"isIndex":false,"isScoreParam":false,"type":"STRING"},"query":{"isIndex":false,"isScoreParam":false,"type":"STRING"}}

但是,我想要的是将这些列名单独地添加到数组/列表中作为

  

[scenario,_duration_1,query]。

但看起来我需要知道键值才能使用json.get(key)方法获取值。

更新2

JSONParser parser = new JSONParser();
JSONObject json = (JSONObject)new JSONParser().parse("{\"columns\":{\"scenario\":{\"type\":\"STRING\",\"isScoreParam\":false,\"isIndex\":false},\"_duration_1\":{\"type\":\"STRING\",\"isScoreParam\":false,\"isIndex\":true},\"query\":{\"type\":\"STRING\",\"isScoreParam\":false,\"isIndex\":false}},\"primaryKeys\":[]}");

JSONObject keys = (JSONObject)json.get("columns");
System.out.println(keys.keySet());

输出,

  

[_ duration_1,场景,查询]

0 个答案:

没有答案