How to extract parameters from a given url

后端 未结 7 574
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-27 05:10

In Java I have:

String params = \"depCity=PAR&roomType=D&depCity=NYC\";

I want to get values of depCity parameters (PA

7条回答
  •  抹茶落季
    2020-11-27 06:04

    It doesn't have to be regex. Since I think there's no standard method to handle this thing, I'm using something that I copied from somewhere (and perhaps modified a bit):

    public static Map> getQueryParams(String url) {
        try {
            Map> params = new HashMap>();
            String[] urlParts = url.split("\\?");
            if (urlParts.length > 1) {
                String query = urlParts[1];
                for (String param : query.split("&")) {
                    String[] pair = param.split("=");
                    String key = URLDecoder.decode(pair[0], "UTF-8");
                    String value = "";
                    if (pair.length > 1) {
                        value = URLDecoder.decode(pair[1], "UTF-8");
                    }
    
                    List values = params.get(key);
                    if (values == null) {
                        values = new ArrayList();
                        params.put(key, values);
                    }
                    values.add(value);
                }
            }
    
            return params;
        } catch (UnsupportedEncodingException ex) {
            throw new AssertionError(ex);
        }
    }
    

    So, when you call it, you will get all parameters and their values. The method handles multi-valued params, hence the List rather than String, and in your case you'll need to get the first list element.

提交回复
热议问题