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

时间:2011-05-05 17:53:40

标签: java regex matcher

在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

我做错了什么?

7 个答案:

答案 0 :(得分: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);
    }
}

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

答案 1 :(得分: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
}

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

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

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

答案 2 :(得分:7)

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

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

答案 3 :(得分:6)

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

首先,如果您不想自己编写内容并只是使用lib,那么请使用Apache的httpcomponents lib的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;
}

答案 4 :(得分:3)

Simple Solution从所有param名称和值中创建地图并使用它:)。

/**
 * This function used provide the pagination resources
 * @param {string} $link : This is page link
 * @param {number} $count : This is page count
 * @param {number} $perPage : This is records per page limit
 * @return {mixed} $result : This is array of records and pagination data
 */
function paginationCompress($link, $count, $perPage = 10) {
    $this->load->library ( 'pagination' );

    $config ['base_url'] = base_url () . $link;
    $config ['total_rows'] = $count;
    $config ['uri_segment'] = SEGMENT;
    $config ['per_page'] = $perPage;
    $config ['num_links'] = 5;
    $config ['full_tag_open'] = '<nav><ul class="pagination">';
    $config ['full_tag_close'] = '</ul></nav>';
    $config ['first_tag_open'] = '<li class="arrow">';
    $config ['first_link'] = 'First';
    $config ['first_tag_close'] = '</li>';
    $config ['prev_link'] = 'Previous';
    $config ['prev_tag_open'] = '<li class="arrow">';
    $config ['prev_tag_close'] = '</li>';
    $config ['next_link'] = 'Next';
    $config ['next_tag_open'] = '<li class="arrow">';
    $config ['next_tag_close'] = '</li>';
    $config ['cur_tag_open'] = '<li class="active"><a href="#">';
    $config ['cur_tag_close'] = '</a></li>';
    $config ['num_tag_open'] = '<li>';
    $config ['num_tag_close'] = '</li>';
    $config ['last_tag_open'] = '<li class="arrow">';
    $config ['last_link'] = 'Last';
    $config ['last_tag_close'] = '</li>';

    $this->pagination->initialize ( $config );
    $page = $config ['per_page'];
    $segment = $this->uri->segment ( SEGMENT );

    return array (
            "page" => $page,
            "segment" => $segment
    );
}


function userListing()
{
    $this->load->model('user_model');

    $this->load->library('pagination');

    $count = $this->user_model->userListingCount();

    $returns = $this->paginationCompress ( "userListing/", $count, 5 );

    $data['userRecords'] = $this->user_model->userListing($returns["page"], $returns["segment"]);

    $this->load->view('includes/header');
    $this->load->view("users", $data);
    $this->load->view('includes/footer');
}

答案 5 :(得分:3)

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

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

答案 6 :(得分:0)

相同,但带有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);
    }
}