I need to get the video id of a YouTube url as follows. https://m.youtube.com/watch?v=9tg3csrFVJw I referred This and this but I could not find a solution.
any help is appreciated.
Try this regex:
v=([^\s&#]*)
Explanation:
v=
literally matches v=()
capturing group , in this case group 1, whose value I want to
capture here[^\s&#]*
matches everything unless a space or & or #. & is necessary as
the version id may not be the last parameter. # is necessary as # can be used as bookmark in a url.You can try that :
final String regex = "v=([^\\s&#]*)";
final String string = " https://m.youtube.com/watch?v=9tg3csrFVJw";
final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(string);
if(matcher.find()) {
System.out.println(matcher.group(1));
}
You can use
val regex =
"^((?:https?:)?//)?((?:www|m)\\.)?((?:youtube\\.com|youtu.be|youtube-nocookie.com))(/(?:[\\w\\-]+\\?v=|feature=|watch\\?|e/|embed/|v/)?)([\\w\\-]+)(\\S+)?\$"