Java Basename

From EggeWiki
Revision as of 23:47, 14 October 2009 by Egge (talk | contribs) (Created page with '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 h…')
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
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>