If you don't need to use a regex, then use URI:
private static final Pattern PARAM_SEPARATOR = Pattern.compile("&");
private static final Pattern PATH_MATCHER = Pattern.compile("/file/d/([^/]+)");
// In query parameter...
public static String getKeyQueryParamFromURI(final String input)
{
final URI uri = URI.create(input);
final String params = uri.getQuery();
if (params == null)
return null;
for (final String param: PARAM_SEPARATOR.split(input))
if (param.startsWith("key="))
return param.substring(4);
return null;
}
// In path...
public static String getPathMatcherFromURI(final String input)
{
final URI uri = URI.create(input);
final String path = uri.getPath();
if (path == null)
return null;
final Matcher m = PATH_MATCHER.matcher(input);
return m.find() ? m.group(1) : null;
}
Note that unlike a regex, you will receive the result unescaped. If for instance the URI reads key=a%20b, this will return you "a b"!
If you insist on using a regex (why?), then do that instead for the query parameter:
private static final Pattern PATTERN = Pattern.compile("(?<=[?&])key=([^&]+)");
public static String getKeyQueryParamFromURI(final String input)
{
final Matcher m = PATTERN.matcher(input);
return m.find() ? m.group(1) : null;
}
But you'll have to unescape the parameter value yourself...
URIwould make your job much easier