Getting specific value from url query string using

2019-10-03 08:06发布

I have a String with a url like this: http://www.website.com/search?productId=1500

How do I get the value of productId with regular expression?

标签: java regex
3条回答
何必那么认真
2楼-- · 2019-10-03 08:43

If you really want to do that:

public static void main(String[] args) throws Exception {
    Pattern pattern = Pattern.compile("http://www.website.com/search\\?productId=(\\d+)");
    Matcher matcher = pattern.matcher("http://www.website.com/search?productId=1500");
    if (matcher.matches()) {
        String productId = matcher.group(1);
    }
}

However, there are libraries to parse URL query arguments and they will also do things like URL-decoding the arguments. Regexes can't do that.

Here's a question on SO that explains how to use libraries and even a code snippet for parsing query string arguments from URLs properly: Parse a URI String into Name-Value Collection

查看更多
爷、活的狠高调
3楼-- · 2019-10-03 09:00

If you know that the desired number is prefixed by productId=, then why not work with substring?

查看更多
狗以群分
4楼-- · 2019-10-03 09:05

I would probably use URLEncodedUtils from Appache Commons.

String url = "http://www.website.com/search?productId=1500";

List<NameValuePair> paramsList = URLEncodedUtils.parse(new URI(url),"utf-8");
for (NameValuePair parameter : paramsList)
    if (parameter.getName().equals("productId"))
        System.out.println(parameter.getValue());

outpit 1500.

But if you really want to use regex you can try

Pattern p = Pattern.compile("[?&]productId=(\\d+)");
Matcher m = p.matcher(url); //  _____________↑ group 1
if (m.find())               // |
    System.out.println(m.group(1));
查看更多
登录 后发表回答