需求

需要获取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;
}