簡體   English   中英

如何從給定的 url 中提取參數

[英]How to extract parameters from a given url

在Java中,我有:

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

我想獲取depCity參數(PAR,NYC)的值。

所以我創建了正則表達式:

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

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

我究竟做錯了什么?

它不必是正則表達式。 因為我認為沒有標准的方法來處理這個事情,所以我使用的是我從某處復制的東西(也許做了一些修改):

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

因此,當您調用它時,您將獲得所有參數及其值。 該方法處理多值參數,因此使用List<String>而不是String ,在您的情況下,您需要獲取第一個列表元素。

不確定您如何使用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
}

但是,如果您只想要值,而不是鍵depCity=那么您可以使用m.group(1)或使用帶有環視的正則表達式:

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

它在與上面相同的 Java 代碼中工作。 它嘗試在depCity=之后depCity=找到開始位置。 然后匹配任何東西,但盡可能少,直到它到達面向&或輸入結束的點。

我有三個解決方案,第三個是Bozho的改進版。

首先,如果你不想自己寫東西而只是使用一個庫,那么使用 Apache 的 httpcomponents 庫的 URIBuilder 類: http ://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/ http/client/utils/URIBuilder.html

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

第二:

// 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;
}

第三:

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

如果您正在開發 Android 應用程序,請嘗試以下操作:

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

如果類路徑上存在spring-web可以使用UriComponentsBuilder

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

簡單的解決方案從所有參數名稱和值中創建映射並使用它:)。

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

相同,但使用 jsonobject:

public static JSONObject getQueryParams2(String url) {
    JSONObject json = new JSONObject();
    try {
        String[] urlParts = url.split("\\?");
        JSONArray array = new  JSONArray();
        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");
                    if(json.has(key)) {
                        array = json.getJSONArray(key);
                        array.put(value);
                        json.put(key, array);
                        array = new JSONArray();
                    } else {
                        array.put(value);
                        json.put(key, array);
                        array = new JSONArray();
                    }
                }
            }
        }
        return json;
    } catch (Exception ex) {
        throw new AssertionError(ex);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM