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
1
  • Tried Pshemo's solution. Commented Jul 29, 2012 at 12:23

4 Answers 4

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

Sign up to request clarification or add additional context in comments.

2 Comments

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?
Actually regular expressions are considered as bad practice 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 will help you a little.
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

Comments

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

Comments

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);

1 Comment

Wouldn't it be better to use strArray[i].split("=", 1)[1] instead of strArray[i].split("=")[1]?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.