解决从类似这样的字符串 c=1;b=12;a=123 中获取b属性的值12 /** * 获取cookie的值 * @param cookies * 类似这样的字符串: * c=1;b=12;a=123 * @param key * @return */public static String getCookieValue(String cookies,
/** * 获取cookie的值 * @param cookies * 类似这样的字符串: * c=1;b=12;a=123 * @param key * @return */ public static String getCookieValue(String cookies, String key) { Pattern pattern = Pattern.compile(key + "[\\s]*=[\\s]*([^;\\s]{1,})"); Matcher matcher = pattern.matcher(cookies); if(matcher.find()){ if(matcher.groupCount() == 1){ return matcher.group(1); } } return null; }测试
public static void main(String[] args) { System.out.println(getCookieValue("c=1;b=12;a=123","b")); System.out.println(getCookieValue("c= 1 ; b= 12 ; a= 123","b")); System.out.println(getCookieValue("c= 1 ; b = 12 ; a= 123;;","a")); System.out.println(getCookieValue("c=bbbb;b=12;a=123","b")); }