簡體   English   中英

正則表達式僅獲取字符串的特定部分

[英]Regex getting a specific part of a string only

例如,我正在嘗試僅獲取以下內容:

-68.06993865966797

從這種類型的輸出:

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

怎么可能只得到字符串

“海拔”:

並以逗號結尾,但在提升后的冒號之間獲取字符串,直到結束該行的逗號

不建議對 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"));
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM