0

I need to extract a randomly generated part of an URL for a Selenium Test in Java.

When the browser opens a page, e.g.:

/edit_person.html?id=eb58cea3a3772ff656987792eb0a8c0f

then I'm able to show the url with:

String url = driver.getCurrentUrl();

but now I need to get only the randomly generated ID after the equals sign.

How do I extract the value of parameter id once I have the entire URL as a string in variable url?

Paolo Moretti
  • 54,162
  • 23
  • 101
  • 92
nacya
  • 21
  • 4
  • 1
    Use the URI class to get the query part, then parse the query part yourself (cut up along `&`, then cut up along `=`) – nhahtdh Sep 26 '12 at 17:40
  • 1
    http://stackoverflow.com/questions/1667278/parsing-query-strings-in-java – Joel Purra Sep 26 '12 at 17:42
  • what have you tried? there are plenty of ways to do this, the `URL` class has methods that make this easy –  Sep 26 '12 at 17:42

2 Answers2

1

URL.getQuery() will give the query portion as a String it is a simple regular expression match to isolate the part you want.

id=(.*) will get you what you want as long as it is the only thing in the query string.

1

This is how managed to solve the problem:

String url = driver.getCurrentUrl();
        URL aURL = new URL(url);
        url = aURL.getQuery();
        String[] id = url.split("=");
        System.out.println(id[1]);  

Thanks to Jarrod Roberson!

nacya
  • 21
  • 4