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
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);
strArray[i].split("=", 1)[1] instead of strArray[i].split("=")[1]?