正则表达式只获取字符串的特定部分

时间:2016-03-22 13:29:28

标签: java regex

我试图仅举例说明:

-68.06993865966797

来自此类型的输出:

{
   "results" : [
      {
         "elevation" : -68.06993865966797,
         "location" : {
            "lat" : 27.85061,
            "lng" : -95.58962
         },
         "resolution" : 152.7032318115234
      }
   ],
   "status" : "OK"
}

如何只能在

之后获取字符串
  

"海拔" :

并以逗号结尾,但在提升后获取冒号之间的字符串,直到结束该行的逗号

1 个答案:

答案 0 :(得分:1)

不建议对JSON数据使用正则表达式。尽管如此,我将两种方式(即正则表达式和JSON解析器)放在一起如下:

import java.util.regex.*;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public static void main(String[] args) throws JSONException {

    String JSON_DATA = "{\n"+
    " \"results\" : [\n"+
    " {\n"+
    " \"elevation\" : -68.06993865966797,\n"+
    " \"location\" : {\n"+
    " \"lat\" : 27.85061,\n"+
    " \"lng\" : -95.58962\n"+
    " },\n"+
    " \"resolution\" : 152.7032318115234\n"+
    " }\n"+
    " ],\n"+
    " \"status\" : \"OK\"\n"+
    "}\n"+
    "";
    // 1. If using REGEX to find all values of "elevation".
    Matcher m = Pattern.compile("\"elevation\"\\s+:\\s+(-?[\\d.]+),").matcher(JSON_DATA);
    while (m.find()) {
        System.out.println("elevation: " + m.group(1));
    }

    // 2. If using a JSON parser
    JSONObject obj = new JSONObject(JSON_DATA);
    JSONArray geodata = obj.getJSONArray("results");
    for (int i = 0; i < geodata.length(); ++i) {
      final JSONObject site = geodata.getJSONObject(i);
      System.out.println("elevation: " + site.getDouble("elevation"));
    }
}