-1

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?

EN A
  • 39
  • 2
  • 7

3 Answers3

8

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));
Pshemo
  • 122,468
  • 25
  • 185
  • 269
1

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

Community
  • 1
  • 1
Erwin Bolwidt
  • 30,799
  • 15
  • 56
  • 79
0

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

Smutje
  • 17,733
  • 4
  • 24
  • 41