How to obtain the last path segment of a URI in java

How to obtain the last path segment of a URI in java

To obtain the last path segment of a URI in Java, you can use the URI class or regular expressions. Here's how to do it using both approaches:

  1. Using the URI Class (Preferred Method):

    You can use the URI class from the Java Standard Library to parse the URI and extract its components. Here's an example:

    import java.net.URI; public class UriExample { public static void main(String[] args) { String urlString = "https://example.com/path/to/resource/file.txt"; URI uri = URI.create(urlString); // Get the last path segment String[] segments = uri.getPath().split("/"); String lastSegment = segments[segments.length - 1]; System.out.println("Last Path Segment: " + lastSegment); } } 

    In this example, we create a URI object from the URL string and then split the path by / to obtain an array of segments. We retrieve the last segment by accessing the last element of the array.

  2. Using Regular Expressions:

    If you prefer using regular expressions, you can achieve the same result with the Pattern and Matcher classes:

    import java.util.regex.Matcher; import java.util.regex.Pattern; public class UriExample { public static void main(String[] args) { String urlString = "https://example.com/path/to/resource/file.txt"; Pattern pattern = Pattern.compile("/([^/]+)$"); Matcher matcher = pattern.matcher(urlString); if (matcher.find()) { String lastSegment = matcher.group(1); System.out.println("Last Path Segment: " + lastSegment); } } } 

    In this example, we use a regular expression (/([^/]+)$) to match the last path segment. The regular expression captures one or more characters that are not / at the end of the string.

Both of these approaches will allow you to obtain the last path segment of a URI in Java. Using the URI class is generally more straightforward and is recommended unless you have specific requirements that necessitate regular expressions.


More Tags

lamp spotfire google-polyline pnp-framework v-model equation-solving gui-testing mouseevent messagebox tabletools

More Java Questions

More Entertainment Anecdotes Calculators

More General chemistry Calculators

More Genetics Calculators

More Organic chemistry Calculators