Reputation: 5645
How can I get the last two parts of a URL. For example if a URL is
http://stackoverflow/java/regex
I would like to get the following
java/regex
The regex "./(.)" will give me the last segment but I struggling to get the last two parts.
Upvotes: 0
Views: 2806
Reputation: 48404
You can try this:
String url = "http://stackoverflow/java/regex";
Pattern pattern = Pattern.compile(".+/(.+/.+)$");
Pattern otherPattern = Pattern.compile(".+/(.+)/.+$");
Matcher matcher = pattern.matcher(url);
if (matcher.find()) {
System.out.println(matcher.group(1));
}
matcher = otherPattern.matcher(url);
if (matcher.find()) {
System.out.println(matcher.group(1));
}
Output:
java/regex
java
Upvotes: 1
Reputation: 272257
I would use the existing URL class and the getPath() method to get the section following the host/port/protocol.
I'd certainly start with an existing class designed to break apart URL components and then work from there. If you use a regexp you're likely to run into and have to cater for lots of edge cases that the URL
class already handles.
Upvotes: 0
Reputation: 17622
You can use java.net.URL
's getPath()
method
URL url = new URL("http://stackoverflow/java/regex");
System.out.println(url.getPath());
Upvotes: 1
Reputation: 121710
Do NOT use regexes for this when Java has URI
!
final URI uri = URI.create("http://stackoverflow/java/regex");
uri.getPath().subString(1); // returns "java/regex"
Upvotes: 7
Reputation: 1495
Simple!
It you have absolute urls:
Pattern p = Pattern.compile("http://(^[/]+)/([^/]+)/([^/]+);
Matcher m = p.matcher(yourURL);
if (m.find()) {
path1 = m.group(2);
path2 = m.group(3);
}
Hope this helps!
Upvotes: 0