How to obtain the last path segment of a URI
is that what you are looking for:
URI uri = new URI("http://example.com/foo/bar/42?param=true");
String path = uri.getPath();
String idStr = path.substring(path.lastIndexOf('/') + 1);
int id = Integer.parseInt(idStr);
alternatively
URI uri = new URI("http://example.com/foo/bar/42?param=true");
String[] segments = uri.getPath().split("/");
String idStr = segments[segments.length-1];
int id = Integer.parseInt(idStr);
How to obtain the last path segment of a URL
Use path.Base to get the last element of a path: path.Base(myUrl.Path)
Run it on the playground.
Extract the last path-segments of a URI or path using RegEx
Use
[^\/]+\/[^\/]+$
See regex proof.
EXPLANATION
--------------------------------------------------------------------------------
[^\/]+ any character except: '\/' (1 or more
times (matching the most amount possible))
--------------------------------------------------------------------------------
\/ '/'
--------------------------------------------------------------------------------
[^\/]+ any character except: '\/' (1 or more
times (matching the most amount possible))
--------------------------------------------------------------------------------
$ before an optional \n, and the end of the
string
Get last path from URL
Just do TrimEnd at the end
public static String GetUserNameInstagramUrl(String url)
{
Uri uri = new Uri(url);
return uri.Segments.Last().TrimEnd('/');
}
Java 8 Get full URL path without last segment (with or without trailing slash)
If all you need is to trim everything after the last "/" (or the second last if the string ends with "/") may be a simple function could solve this:
public static void main(String[] args){
Function<String,String> trimUrlString = s -> {
s = s.endsWith("/") ? s.substring(0, s.length()-1) : s;
return s.substring(0, s.lastIndexOf('/')+1);
};
String u1 = "localhost:8080/myapp";
System.out.println(trimUrlString.apply(u1));
String u2 = "https://myapp-dev.myhost.com/app/";
System.out.println(trimUrlString.apply(u2));
}
//output: localhost:8080/ https://myapp-dev.myhost.com/
EDIT
Another aproach which might be shorter is to chain two replaceAll calls :
myString.replaceAll("/$", "").replaceAll("/[^/]+$", "/");
The first call will remove a forward slash at the end if any, if there is no slash at the end myString
remains the same. The second call will then replace every char after the last /
which is not a /
Some test cases with your examples:
String[] urls = {"localhost:8080/myapp",
"https://myapp-dev.myhost.com/app/test.pdf",
"http://myapp-dev.host.com/app/",
"http://app.host.com:8080/app/app2"};
for(String url : urls){
String s = url.replaceAll("/$", "").replaceAll("/[^/]+$", "/");
System.out.println(url);
System.out.println(s);
System.out.println();
}
What is the fastest way to find the last part of a url path?
I do not think that it can be improved. The short answer is that because the search for the last index is a simple operation, it can be implemented with a fast algorithm (directly in the String class!) and it would be difficult for a regular expression to be as fast as this.
The second access to the String, as you can see, couldn't cost less: it is just the initialisation of the new String.
It could have been faster if there was a dedicated method implemented directly in the String class.
If you want more details, you can see by yourself the code in the JDK. Copied here for your convenience.
The following code is the implementation of the method lastIndexOf() in my JDK:
public int lastIndexOf(int ch, int fromIndex) {
int min = offset;
char v[] = value;
int i = offset + ((fromIndex >= count) ? count - 1 : fromIndex);
if (ch < Character.MIN_SUPPLEMENTARY_CODE_POINT) {
// handle most cases here (ch is a BMP code point or a
// negative value (invalid code point))
for (; i >= min ; i--) {
if (v[i] == ch) {
return i - offset;
}
}
return -1;
}
int max = offset + count;
if (ch <= Character.MAX_CODE_POINT) {
// handle supplementary characters here
char[] surrogates = Character.toChars(ch);
for (; i >= min; i--) {
if (v[i] == surrogates[0]) {
if (i + 1 == max) {
break;
}
if (v[i+1] == surrogates[1]) {
return i - offset;
}
}
}
}
return -1;
}
Being implemented directly in the String class, it has access to its private members:
/** The value is used for character storage. */
private final char value[];
/** The offset is the first index of the storage that is used. */
private final int offset;
/** The count is the number of characters in the String. */
private final int count;
It is not working on substrings.
In the same time, the substring method is very fast in Java because it does not create a new array of char, but it simply creates a new String object changing the offset and the count:
public String substring(int beginIndex, int endIndex) {
if (beginIndex < 0) {
throw new StringIndexOutOfBoundsException(beginIndex);
}
if (endIndex > count) {
throw new StringIndexOutOfBoundsException(endIndex);
}
if (beginIndex > endIndex) {
throw new StringIndexOutOfBoundsException(endIndex - beginIndex);
}
return ((beginIndex == 0) && (endIndex == count)) ? this :
new String(offset + beginIndex, endIndex - beginIndex, value);
}
// Package private constructor which shares value array for speed.
String(int offset, int count, char value[]) {
this.value = value;
this.offset = offset;
this.count = count;
}
Get the last path of URL
Just replace:
string serviceName = _uri.Segments.LastOrDefault();
With:
string serviceName = _uri.Segments.LastOrDefault().Split(new[]{';'}).First();
If you need something more flexible, where you can specify what characters to include or skip, you could do something like this (slightly messy, you should probably extract parts of this as separate variables, etc):
// Note the _ and - characters in this example:
Uri _uri = new Uri("https://ldmrrt.ct/odata/GBSRM/User_ex1-ex2;v=2;mp");
// This will return a string: "User_ex1-ex2"
string serviceName =
new string(_uri.Segments
.LastOrDefault()
.TakeWhile(c => Char.IsLetterOrDigit(c)
|| (new char[]{'_', '-'}).Contains(c))
.ToArray());
Update, in response to what I understand to be a question below :) :
You could just use a String.Replace()
for that, or you could use filtering by doing something like this:
// Will return: "Userexex2v=2mp"
string serviceName =
new string(_uri.Segments
.LastOrDefault()
.Where(c =>
!Char.IsPunctuation(c) // Ignore punctuation
// ..and ignore any "_" or "-":
&& !(new char[]{'_', '-'}).Contains(c))
.ToArray());
If you use this in production, mind you, be sure to clean it up a little, e.g. by splitting into several variables, and defining your char[]-array prior to usage.
Getting the last part of the referrer url
This will give you XYZ.html :
String url = "http://localhost:8080/TEST/XYZ.html";
url = url.substring(url.lastIndexOf("/") + 1);
Best way to extract last segment of URI in Ruby
I would use a proper URI parser like the one of the URI module to get the path from the URI. Then split it at /
and get the last part of it:
require 'uri'
URI(uri).path.split('/').last
How to get the last path in a URL?
Try:
$url = 'http://blabla/blablabla/dut2a/news.php';
$tokens = explode('/', $url);
echo $tokens[sizeof($tokens)-2];
Assuming $tokens
has at least 2 elements.
Related Topics
Java - How to Receive Point Coordinates After Mouse Button Release (Jfreechart)
Registering Multiple Keystores in Jvm
How to Show Jrbeancollectiondatasource Data with Help of Table Component
Iterating Through a List in Reverse Order in Java
Why Static Fields Are Not Initialized in Time
Java 8, Streams to Find the Duplicate Elements
Efficiently Compute Intersection of Two Sets in Java
Why Does My Spring Boot App Always Shutdown Immediately After Starting
How to Serve Jsps from Inside a Jar in Lib, or Is There a Workaround
What Is the Best/Simplest Way to Read in an Xml File in Java Application
"File Not Found" When Running New Libgdx Project
When Does Hashset 'Add' Method Calls Equals
Pick a Random Value from an Enum
Multiple Packages in Context:Component-Scan, Spring Config
Java.Sql.Sqlexception: Incorrect String Value: '\Xf0\X9F\X91\Xbd\Xf0\X9F...'