How can I extract the value of the bookid
from this string using Java?
href="http://www.books.com/?bookname=cooking&bookid=12345678&bookprice=123.45">cooking book
How can I extract the value of the bookid
from this string using Java?
href="http://www.books.com/?bookname=cooking&bookid=12345678&bookprice=123.45">cooking book
Normally you should use some parser but if your String is really this short then maybe regular expression can be option like
String s="href=\"http://www.books.com/?bookname=cooking&bookid=12345678&bookprice=123.45\">cooking book";
Pattern p= Pattern.compile("(?<=bookid=)\\d+");
Matcher m=p.matcher(s);
if (m.find())
System.out.println(m.group());
output:
12345678
A very simple answer would be
String[] queryParams = url.split("\\?")[1].split("&");
This would give you all the parameters in a=b form in each of the element. You can then just split the needed param.
But ideally you should extract the value by param name
Pshemo you beat me to it but you can also use this: "(id\=[0-9]*)"
and try RegexPlanet to try out your regex and retrieve the escapped string in java format
You can use the following code snippet:
String str = "href=\"http://www.books.com/?bookname=cooking&bookid=12345678&bookprice=123.45\">cooking book";
String[] strArray = str.split("&");
String bookId = "";
for(int i=0;i<strArray.length;i++)
{
if(strArray[i].startsWith("bookid"))
{
bookId = strArray[i].split("=")[1];
}
}
System.out.println("Book ID = "+bookId);