0

I have a bunch of strings like this:

Some text, bla-bla http://www.easypolls.net/poll.html?p=51e5a300e4b084575d8568bb#.UeWjBcCzaaA.twitter

And I need to parse this String to two:

Some text, bla-bla

http://www.easypolls.net/poll.html?p=51e5a300e4b084575d8568bb#.UeWjBcCzaaA.twitter

I need separate them, but, of course, it's enough to parse only URL.

Can you help me, how can I parse url from string like this.

JohnDow
  • 1,060
  • 4
  • 18
  • 40
  • Split before `http:...`? – Sotirios Delimanolis Jul 17 '13 at 18:34
  • Did you do any research of your own before asking here? I just googled "extract url from string" and there are a lot of posts that may be helpful that came up! :) – eldris Jul 17 '13 at 18:35
  • You might be looking for a [URL regex](http://stackoverflow.com/questions/161738/what-is-the-best-regular-expression-to-check-if-a-string-is-a-valid-url).. – bbill Jul 17 '13 at 18:38

4 Answers4

2

This depends on how robust you want your parser to be. If you can reasonably expect every url to start with http://, then you can use

  string.indexOf("http://"); 

This returns the index of the first character of the string you pass in (and -1 if the string does not appear).

Full code to return a substring with just the URL:

  string.substring(string.indexOf("http://"));

Here's the documentation for Java's String class. Let this become your friend in programming! http://docs.oracle.com/javase/7/docs/api/java/lang/String.html

neubert
  • 14,208
  • 21
  • 90
  • 172
Wieschie
  • 479
  • 7
  • 15
2

By using split :

    String str = "Some text, bla-bla http://www.easypolls.net/poll.html?p=51e5a300e4b084575d8568bb#.UeWjBcCzaaA.twitter";
    String [] ar = str.split("http\\.*");
    System.out.println(ar[0]);
    System.out.println("http"+ar[1]);
Grisha Weintraub
  • 7,435
  • 1
  • 21
  • 43
1

Try something like this:

    String string = "sometext http://www.something.com";
    String url = string.substring(string.indexOf("http"), string.length());
    System.out.println(url);

or use split.

Collin
  • 306
  • 3
  • 8
-2

I know in PHP you'd be able to run the explode() (http://www.php.net/manual/en/function.explode.php) function. You'd choose which character you want to explode at. For instance, you could explode at "http://"

So running the code via PHP would look like:

$string  = "Some text, bla-bla http://www.easypolls.net/poll.html?p=51e5a300e4b084575d8568bb#.UeWjBcCzaaA.twitter";
$pieces = explode("http://", $string);
echo $pieces[0]; // Would print "Some text, bla-bla"
echo $pieces[1]; // Would print "www.easypolls.net/poll.html?p=51e5a300e4b084575d8568bb#.UeWjBcCzaaA.twitter"
JoE
  • 1
  • 1