Im reading a file which contains Urls like (http://www.espncricinfo.com/netstorage/817215.json?xhr=1) , How to get the string like (http://www.espncricinfo.com/) before 3rd ('/').
Asked
Active
Viewed 86 times
1
-
3have u considered using url.getHost() instead? – nafas Aug 04 '15 at 15:08
-
Take a look at this question about getting the [nth index of a character in a string](http://stackoverflow.com/questions/3976616/how-to-find-nth-occurrence-of-character-in-a-string). If you implement that its simple to use in in conjunction with `substring()`. – Ryan Jackman Aug 04 '15 at 15:09
-
Thanks nafas it is working . and other comments are also valid for me and i will also trying to solve it using regex. – Aug 04 '15 at 15:22
4 Answers
1
One way: make use of RegEx
,
String link = "http://www.espncricinfo.com/netstorage/817215.json?xhr=1";
Pattern pattern = Pattern.compile("((https?://)[^/]+/?)");
Matcher matcher = pattern.matcher(link);
while (matcher.find()) {
System.out.println(matcher.group(1));
}
better way: Make use of URL
package:
URL url = new URL(link);
System.out.println(url.getHost());

nafas
- 5,283
- 3
- 29
- 57
-
-
-
@sharief try it now, it should only pick urls starting with http:// or https:// – nafas Aug 04 '15 at 15:30
0
Use java.net.URL:
URL url = new URL("http://www.espncricinfo.com/netstorage/817215.json?xhr=1");
String before_3rd = url.getProtocol() +"://" + url.getHost() + url.getPort();

Anton Krosnev
- 3,964
- 1
- 21
- 37
0
You can use the URI
method resolve
:
URI uri = URI.create("http://www.espncricinfo.com/netstorage/817215.json?xhr=1&a=b");
String result = uri.resolve("/").toString();
This method basically uses your original URI as the basis to calculating a similar URI with a different path. By giving it the path "/"
it means you will get back the original base URI (including user info or port if they were there). Printing the result above will give:
http://www.espncricinfo.com/
And if your original URL was:
http://user:pass@www.espncricinfo.com:8080/netstorage/817215.json?xhr=1
The result would be:
http://user:pass@www.espncricinfo.com:8080/

RealSkeptic
- 33,993
- 7
- 53
- 79