Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getting the youtube id from a link

Tags:

I got this code to get the youtube id from the links like www.youtube.com/watch?v=xxxxxxx

  URL youtubeURL = new URL(link);
  youtubeURL.getQuery();

basically this will get me the id easily v=xxxxxxxx

but I noticed sometime youtube links will be like this

http://gdata.youtube.com/feeds/api/videos/xxxxxx

I am getting the links from a feed so do I need to build a regex for that or theres a parser to get that for me ?

like image 672
Peril Avatar asked Oct 11 '11 17:10

Peril


People also ask

How do I extract a link from YouTube?

Locate a URL using a browser on a computer In your browser, open YouTube. Find and click the video whose URL you want to see. The URL of the video will be in the address bar.

How do I verify a YouTube video ID?

you can hit this: http://gdata.youtube.com/feeds/api/videos/VIDEO_ID (Page now returns: "No longer available".) There's no way you can check the validity of the ID with RegEx, since not all alpha-numeric values are valid ID's.


2 Answers

Tried the other ones but failed in my case - adjusted the regex to fit for my urls

String pattern = "(?<=watch\\?v=|/videos/|embed\\/)[^#\\&\\?]*";          Pattern compiledPattern = Pattern.compile(pattern);     Matcher matcher = compiledPattern.matcher(url);      if(matcher.find()){         return matcher.group();     } 

This one works for: (you could also implement a security check youtubeid length = 11 )

http://www.youtube.com/embed/Woq5iX9XQhA?html5=1

http://www.youtube.com/watch?v=384IUU43bfQ

http://gdata.youtube.com/feeds/api/videos/xTmi7zzUa-M&whatever

Woq5iX9XQhA

384IUU43bfQ

xTmi7zzUa-M

like image 199
max Avatar answered Oct 22 '22 23:10

max


public static String getYoutubeVideoId(String youtubeUrl)
 {
 String video_id="";
  if (youtubeUrl != null && youtubeUrl.trim().length() > 0 && youtubeUrl.startsWith("http"))
 {

String expression = "^.*((youtu.be"+ "\\/)" + "|(v\\/)|(\\/u\\/w\\/)|(embed\\/)|(watch\\?))\\??v?=?([^#\\&\\?]*).*"; // var regExp = /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#\&\?]*).*/;
 CharSequence input = youtubeUrl;
 Pattern pattern = Pattern.compile(expression,Pattern.CASE_INSENSITIVE);
 Matcher matcher = pattern.matcher(input);
 if (matcher.matches())
 {
String groupIndex1 = matcher.group(7);
 if(groupIndex1!=null && groupIndex1.length()==11)
 video_id = groupIndex1;
 }
 }
 return video_id;
 }
like image 35
samirprogrammer Avatar answered Oct 22 '22 22:10

samirprogrammer