Java Basename

From EggeWiki
Jump to navigation Jump to search

Ruby contains a nice build in function to get the basename of a file. <geshi> File.basename('https://www.theeggeadventure.com/wikimedia/index.php') => "index.php" </geshi>

The handy function is not present in the JDK. Here's my Java version of the function.

<geshi> private static final Pattern BASENAME = Pattern.compile(".*?([^/]*)$");

public static String basename(URL url) { return basename(url.getPath()); }

public static String basename(String url) { Matcher matcher = BASENAME.matcher(url); if (matcher.matches()) { return matcher.group(1); } else { throw new IllegalArgumentException("Can't parse " + url); } } </geshi>