import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main(String[] args) {
final String regex = "#\n"
+ "# Inspired by http://stackoverflow.com/questions/6556559/youtube-api-extract-video-id\n"
+ "# Example: https://www.youtube.com/watch?v=o8QuLYXKNCg&rel=0&autoplay=1\n"
+ "#\n"
+ "# Match any youtube URL\n"
+ " (?:https?://)? # Optional scheme. Either http or https\n"
+ " (?:www\\.)? # Optional www subdomain\n"
+ " (?: # Group host alternatives\n"
+ " youtu\\.be/ # Either youtu.be,\n"
+ " | youtube\\.com # or youtube.com\n"
+ " (?: # Group path alternatives\n"
+ " /embed/ # Either /embed/\n"
+ " | /v/ # or /v/\n"
+ " | /watch\\?v= # or /watch\\?v=\n"
+ " ) # End path alternatives.\n"
+ " )? # End host alternatives.\n"
+ " ([\\w-]{10,12}) # Allow 10-12 for 11 char youtube id.\n"
+ " (?:[&?](.*)) # Optional Parameters\n"
+ " $";
final String string = "https://www.youtube.com/watch?v=o8QuLYXKNCg&rel=0&autoplay=1&autoplay=2&autoplay=3&autoplay=4";
final Pattern pattern = Pattern.compile(regex, Pattern.COMMENTS);
final Matcher matcher = pattern.matcher(string);
if (matcher.find()) {
System.out.println("Full match: " + matcher.group(0));
for (int i = 1; i <= matcher.groupCount(); i++) {
System.out.println("Group " + i + ": " + matcher.group(i));
}
}
}
}
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for Java, please visit: https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html