正則表達式-獲取Json屬性值


需求

  需要獲取json的字符串參數中的某個屬性的值,只用json轉對象后再獲取層級比較多,所以使用簡單的正則表達式進行獲取

具體實現

  public static void main(String[] args) {
    String data = "{\"code\":1,\"msg\":\"操作成功!\",\"success\":true,\"data\":{\"code\":\"3100183130\",\"number\":\"39518133\",\"issue_date\":\"20190308\",\"amount\":\"339.62\"}}";
    List<String> failList = searchMatch(data,"code\":\"(\\w+)?\"",1);
    System.out.println(failList.toString());
}

   /**
 * 正則表達式 查找匹配的字符串
 * @param withinText 字符串
 * @param regString 正則表達式
 * @param index 提取正則匹配到字符串的哪一部分 0整串,1第一個()的內容,2第二個()...
 * @return 匹配值列表
 */
public static List<String> searchMatch(String withinText, String regString,int index) {
    List<String> resList = new ArrayList<>();
    String value = null;
    Pattern pattern = Pattern.compile(regString);
    Matcher matcher = pattern.matcher(withinText);
    if (matcher.find()) {
        matcher.reset();
        while (matcher.find()) {
            System.out.println("匹配到的整串-->" + matcher.group(0));
            value = matcher.group(index);
            System.out.println("整串中指定的子串-->" + value);
            resList.add(value);
        }
    }
    return resList;
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM