0

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
ant
  • 22,634
  • 36
  • 132
  • 182
Amir Ghahrai
  • 618
  • 1
  • 7
  • 22

4 Answers4

4

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
  • 122,468
  • 25
  • 185
  • 269
  • Thanks Pshemo, Actually the String is the full HTML source of a page where this is just a part where the bookid is present, so I guess I can use your solution for that as well? – Amir Ghahrai Jul 28 '12 at 19:39
  • Actually regular expressions are considered as [bad practice](http://stackoverflow.com/a/1732454/1393766) for parsing HTML. For example my solution will find number that is preceded by "bookid=" so if your HTML will contain that combination before your href (for example in some comment or other content generated by user) you can have bad results. For parsing entire HTML code use special tools designed for that. Maybe [this](http://stackoverflow.com/questions/3152138/what-are-the-pros-and-cons-of-the-leading-java-html-parsers) will help you a little. – Pshemo Jul 28 '12 at 19:52
1

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

afrin216
  • 2,295
  • 1
  • 14
  • 17
0

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

ricardoespsanto
  • 1,000
  • 10
  • 34
0

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);
A Null Pointer
  • 2,261
  • 3
  • 26
  • 28
  • Wouldn't it be better to use `strArray[i].split("=", 1)[1]` instead of `strArray[i].split("=")[1]`? – nkr Jul 28 '12 at 19:32