Java tutorial
//package com.java2s; import java.net.URI; import java.net.URISyntaxException; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Main { /** * Extract the UUID part from a MusicBrainz identifier. * * This function takes a MusicBrainz ID (an absolute URI) as the input * and returns the UUID part of the URI, thus turning it into a relative * URI. If <code>uriStr</code> is null or a relative URI, then it is * returned unchanged. * * The <code>resType</code> parameter can be used for error checking. * Set it to 'artist', 'release', or 'track' to make sure * <code>uriStr</code> is a syntactically valid MusicBrainz identifier * of the given resource type. If it isn't, an * <code>IllegalArgumentException</code> exception is raised. This error * checking only works if <code>uriStr</code> is an absolute URI, of course. * * Example: * >>> MBUtils.extractUuid('http://musicbrainz.org/artist/c0b2500e-0cef-4130-869d-732b23ed9df5', 'artist') * 'c0b2500e-0cef-4130-869d-732b23ed9df5' * * @param uriStr A string containing a MusicBrainz ID (an URI), or null * @param resType A string containing a resource type * @return A String containing a relative URI or null * @throws URISyntaxException */ public static String extractUuid(String uriStr, String resType) { if (uriStr == null) { return null; } URI uri; try { uri = new URI(uriStr); } catch (URISyntaxException e) { return uriStr; // not really a valid URI, probably the UUID } if (uri.getScheme() == null) { return uriStr; // not really a valid URI, probably the UUID } if (!"http".equals(uri.getScheme()) || !"musicbrainz.org".equals(uri.getHost())) { throw new IllegalArgumentException(uri.toString() + " is no MB ID"); } String regex = "^/(label|artist|release-group|release|recording|work|collection)/([^/]*)$"; Pattern p = Pattern.compile(regex); Matcher m = p.matcher(uri.getPath()); if (m.matches()) { if (resType == null) { return m.group(2); } else { if (resType.equals(m.group(1))) { return m.group(2); } else { throw new IllegalArgumentException("expected '" + resType + "' Id"); } } } else { throw new IllegalArgumentException("'" + uriStr + " is no valid MB id"); } } }