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

gos*_*din 19 java regex matcher

在Java中我有:

String params = "depCity=PAR&roomType=D&depCity=NYC";
Run Code Online (Sandbox Code Playgroud)

我想获得depCity参数值(PAR,NYC).

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

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

m.find()是假的.m.groups()正在恢复IllegalArgumentException.

我究竟做错了什么?

Boz*_*zho 39

它不一定是正则表达式.因为我认为没有标准的方法可以处理这个问题,所以我使用的是从某个地方复制的东西(也许还有一些修改过):

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

因此,当您调用它时,您将获得所有参数及其值.该方法处理多值参数,因此List<String>而不是String,在您的情况下,您将需要获取第一个列表元素.

  • 地图是一个非常核心和简单的概念,因此我没有看到它们的问题. (8认同)
  • #之后的部分未提交给服务器 (5认同)
  • 此解决方案不考虑在"#"之后附加在末尾的URL的片段部分.在http urls中,这部分引用了一个内部锚点.因此必须在"#"处再次拆分变量查询,然后必须进一步处理返回数组的索引0. (3认同)

Sta*_*erg 14

不知道你如何使用findgroup,但能正常工作:

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
}
Run Code Online (Sandbox Code Playgroud)

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

Pattern p = Pattern.compile("(?<=depCity=).*?(?=&|$)");
Run Code Online (Sandbox Code Playgroud)

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


use*_*755 8

我有三个解决方案,第三个是Bozho的改进版本.

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

new URIBuilder("http://...").getQueryParams()...
Run Code Online (Sandbox Code Playgroud)

第二:

// 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;
}
Run Code Online (Sandbox Code Playgroud)

第二:

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;
}
Run Code Online (Sandbox Code Playgroud)


War*_*an- 8

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

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


小智 5

如果类路径上存在spring-web可以使用UriComponentsBuilder

MultiValueMap<String, String> queryParams =
            UriComponentsBuilder.fromUriString(url).build().getQueryParams();
Run Code Online (Sandbox Code Playgroud)