例子1:
现有json:
({"code":"200","json":["111"],"message":"true"})
从中提取json的value数据。
直接上代码如下:
import java.util.ArrayList; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Snippet { public static void main(String[] args) { ArrayList json = new ArrayList(); json.add("111"); User user = new User(); user.setJson(json); user.setCode("200"); user.setMessage("true"); String string = "(" + JSON.toJSONString(user) + ")"; // String regex = ""json":(.*?),"message"";// 使用非贪婪模式! Pattern pattern = Pattern.compile("\["(.*?)"\]"); Matcher matcher = pattern.matcher(string); while (matcher.find()) { System.out.println(matcher.group(1)); } } }
例子2:
String str = "我是[001]真心求救的[002],你能帮帮我吗"; Pattern pattern = Pattern.compile("\[(.*?)\]"); Matcher matcher = pattern.matcher(str); while(matcher.find()){ System.out.println(matcher.group(1)); }
例子3:
public static void main(String[] args) { String parse="[{CSTM_NO:"11118",CSTM_NAME:"广东XX电力有限公司",FIX_GNL:"111810158",FIX_ACC:"D201306070003",OP_FLAG:"正常",BUSS_KIND_NAME:"三个月定期存款",BAL:"25,178,750.00",AVAL_BAL:"25,178,750.00",OP_DATE:"2013-06-07",DUE_DATE:"2013-12-07",ROWNUM_:1,idx:0},{CSTM_NO:"11118",CSTM_NAME:"广东XX电力有限公司",FIX_GNL:"111810158",FIX_ACC:"D201306070002",OP_FLAG:"正常",BUSS_KIND_NAME:"三个月定期存款",BAL:"25,178,750.00",AVAL_BAL:"25,178,750.00",OP_DATE:"2013-06-07",DUE_DATE:"2013-12-07",ROWNUM_:3,idx:2},{CSTM_NO:"11118",CSTM_NAME:"广东XX电力有限公司",FIX_GNL:"111810158",FIX_ACC:"D201306070005",OP_FLAG:"正常",BUSS_KIND_NAME:"三个月定期存款",BAL:"25,178,750.00",AVAL_BAL:"25,178,750.00",OP_DATE:"2013-06-07",DUE_DATE:"2013-12-07",ROWNUM_:4,idx:3}]"; String regex="FIX_ACC:(.*?),OP_FLAG";//别忘了使用非贪婪模式! Matcher matcher=Pattern.compile(regex).matcher(parse); while(matcher.find()) { String ret=matcher.group(1); System.out.println(ret); } }
总结:
(.*?)这个拿出来,左边括号左边是左边界,右边括号右边是右边界,选对后直接匹配,即可拿到