如何从给定的url中提取参数

时间:2022-07-07 21:24:02

In Java I have:

在Java中我有:

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

I want to get values of depCity parameters (PAR,NYC).

我想要得到depCity参数的值(PAR,NYC)。

So I created regex:

所以我创建了正则表达式:

String regex = "depCity=([^&]+)";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(params);

m.find() is returning false. m.groups() is returning IllegalArgumentException.

m.find()返回false。m.groups()返回IllegalArgumentException。

What am I doing wrong?

我做错了什么?

6 个解决方案

#1


39  

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):

它不必是regex。因为我认为没有标准的方法来处理这个东西,所以我使用的是我从某个地方复制过来的东西(也许修改了一点):

public static Map<String, List<String>> getQueryParams(String url) {
    try {
        Map<String, List<String>> params = new HashMap<String, List<String>>();
        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<String> values = params.get(key);
                if (values == null) {
                    values = new ArrayList<String>();
                    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<String> rather than String, and in your case you'll need to get the first list element.

所以,当你调用它时,你会得到所有的参数和它们的值。该方法处理多值参数,因此列表 而不是字符串,在您的示例中,您需要获取第一个列表元素。

#2


13  

Not sure how you used find and group, but this works fine:

不知道你是如何使用find和group的,但是这个方法很有效:

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

try {
    Pattern p = Pattern.compile("depCity=([^&]+)");
    Matcher m = p.matcher(params);
    while (m.find()) {
        System.out.println(m.group());
    } 
} catch (PatternSyntaxException ex) {
    // error handling
}

However, If you only want the values, not the key depCity= then you can either use m.group(1) or use a regex with lookarounds:

但是,如果您只想要值,而不是键depCity=那么您可以使用m.g(1)或使用正则表达式的正则表达式:

Pattern p = Pattern.compile("(?<=depCity=).*?(?=&|$)");

It works in the same Java code as above. It tries to find a start position right after depCity=. Then matches anything but as little as possible until it reaches a point facing & or end of input.

它使用与上面相同的Java代码。它试图在depCity=之后找到一个起始位置。然后匹配任何东西,但尽可能地少,直到它到达一个点,面对和或结束的输入。

#3


7  

If you are developing an Android application, try this:

如果您正在开发Android应用程序,请尝试以下方法:

String yourParam = null;
 Uri uri = Uri.parse(url);
        try {
            yourParam = URLDecoder.decode(uri.getQueryParameter(PARAM_NAME), "UTF-8");
        } catch (UnsupportedEncodingException exception) {
            exception.printStackTrace();
        }

#4


5  

I have three solutions, the third one is an improved version of Bozho's.

我有三种解决方案,第三种是改良版的博措。

First, if you don't want to write stuff yourself and simply use a lib, then use Apache's httpcomponents lib's URIBuilder class: http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/client/utils/URIBuilder.html

首先,如果您不希望自己编写内容并使用lib,那么请使用Apache的httpcomponent lib的URIBuilder类:http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/client/utils/URIBuilder.html

new URIBuilder("http://...").getQueryParams()...

Second:

第二:

// overwrites duplicates
import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URLEncodedUtils;
public static Map<String, String> readParamsIntoMap(String url, String charset) throws URISyntaxException {
    Map<String, String> params = new HashMap<>();

    List<NameValuePair> result = URLEncodedUtils.parse(new URI(url), charset);

    for (NameValuePair nvp : result) {
        params.put(nvp.getName(), nvp.getValue());
    }

    return params;
}

Second:

第二:

public static Map<String, List<String>> getQueryParams(String url) throws UnsupportedEncodingException {
    Map<String, List<String>> params = new HashMap<String, List<String>>();
    String[] urlParts = url.split("\\?");
    if (urlParts.length < 2) {
        return params;
    }

    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");
        }

        // skip ?& and &&
        if ("".equals(key) && pair.length == 1) {
            continue;
        }

        List<String> values = params.get(key);
        if (values == null) {
            values = new ArrayList<String>();
            params.put(key, values);
        }
        values.add(value);
    }

    return params;
}

#5


2  

Simple Solution create the map out of all param name and values and use it :).

简单的解决方案从所有参数名和值中创建映射并使用它:)。

import org.apache.commons.lang3.StringUtils;

    public String splitURL(String url, String parameter){
                HashMap<String, String> urlMap=new HashMap<String, String>();
                String queryString=StringUtils.substringAfter(url,"?");
                for(String param : queryString.split("&")){
                    urlMap.put(StringUtils.substringBefore(param, "="),StringUtils.substringAfter(param, "="));
                }
                return urlMap.get(parameter);
            }

#6


2  

If spring-web is present on classpath, UriComponentsBuilder can be used.

如果在类路径中存在spring-web,则可以使用UriComponentsBuilder。

MultiValueMap<String, String> queryParams =
            UriComponentsBuilder.fromUriString(url).build().getQueryParams();

#1


39  

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):

它不必是regex。因为我认为没有标准的方法来处理这个东西,所以我使用的是我从某个地方复制过来的东西(也许修改了一点):

public static Map<String, List<String>> getQueryParams(String url) {
    try {
        Map<String, List<String>> params = new HashMap<String, List<String>>();
        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<String> values = params.get(key);
                if (values == null) {
                    values = new ArrayList<String>();
                    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<String> rather than String, and in your case you'll need to get the first list element.

所以,当你调用它时,你会得到所有的参数和它们的值。该方法处理多值参数,因此列表 而不是字符串,在您的示例中,您需要获取第一个列表元素。

#2


13  

Not sure how you used find and group, but this works fine:

不知道你是如何使用find和group的,但是这个方法很有效:

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

try {
    Pattern p = Pattern.compile("depCity=([^&]+)");
    Matcher m = p.matcher(params);
    while (m.find()) {
        System.out.println(m.group());
    } 
} catch (PatternSyntaxException ex) {
    // error handling
}

However, If you only want the values, not the key depCity= then you can either use m.group(1) or use a regex with lookarounds:

但是,如果您只想要值,而不是键depCity=那么您可以使用m.g(1)或使用正则表达式的正则表达式:

Pattern p = Pattern.compile("(?<=depCity=).*?(?=&|$)");

It works in the same Java code as above. It tries to find a start position right after depCity=. Then matches anything but as little as possible until it reaches a point facing & or end of input.

它使用与上面相同的Java代码。它试图在depCity=之后找到一个起始位置。然后匹配任何东西,但尽可能地少,直到它到达一个点,面对和或结束的输入。

#3


7  

If you are developing an Android application, try this:

如果您正在开发Android应用程序,请尝试以下方法:

String yourParam = null;
 Uri uri = Uri.parse(url);
        try {
            yourParam = URLDecoder.decode(uri.getQueryParameter(PARAM_NAME), "UTF-8");
        } catch (UnsupportedEncodingException exception) {
            exception.printStackTrace();
        }

#4


5  

I have three solutions, the third one is an improved version of Bozho's.

我有三种解决方案,第三种是改良版的博措。

First, if you don't want to write stuff yourself and simply use a lib, then use Apache's httpcomponents lib's URIBuilder class: http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/client/utils/URIBuilder.html

首先,如果您不希望自己编写内容并使用lib,那么请使用Apache的httpcomponent lib的URIBuilder类:http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/client/utils/URIBuilder.html

new URIBuilder("http://...").getQueryParams()...

Second:

第二:

// overwrites duplicates
import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URLEncodedUtils;
public static Map<String, String> readParamsIntoMap(String url, String charset) throws URISyntaxException {
    Map<String, String> params = new HashMap<>();

    List<NameValuePair> result = URLEncodedUtils.parse(new URI(url), charset);

    for (NameValuePair nvp : result) {
        params.put(nvp.getName(), nvp.getValue());
    }

    return params;
}

Second:

第二:

public static Map<String, List<String>> getQueryParams(String url) throws UnsupportedEncodingException {
    Map<String, List<String>> params = new HashMap<String, List<String>>();
    String[] urlParts = url.split("\\?");
    if (urlParts.length < 2) {
        return params;
    }

    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");
        }

        // skip ?& and &&
        if ("".equals(key) && pair.length == 1) {
            continue;
        }

        List<String> values = params.get(key);
        if (values == null) {
            values = new ArrayList<String>();
            params.put(key, values);
        }
        values.add(value);
    }

    return params;
}

#5


2  

Simple Solution create the map out of all param name and values and use it :).

简单的解决方案从所有参数名和值中创建映射并使用它:)。

import org.apache.commons.lang3.StringUtils;

    public String splitURL(String url, String parameter){
                HashMap<String, String> urlMap=new HashMap<String, String>();
                String queryString=StringUtils.substringAfter(url,"?");
                for(String param : queryString.split("&")){
                    urlMap.put(StringUtils.substringBefore(param, "="),StringUtils.substringAfter(param, "="));
                }
                return urlMap.get(parameter);
            }

#6


2  

If spring-web is present on classpath, UriComponentsBuilder can be used.

如果在类路径中存在spring-web,则可以使用UriComponentsBuilder。

MultiValueMap<String, String> queryParams =
            UriComponentsBuilder.fromUriString(url).build().getQueryParams();