Android Jsoup从所选元素中获取YouTube视频ID

时间:2015-01-21 16:30:04

标签: android jsoup element

Rss String:

<description>
<a href="https://www.facebook.com/l.php?u=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%39s2zWNZydiI&amp;h=aAQEbhn3&amp;s=1" id="" title="" target="" onclick="LinkshimAsyncLink.referrer_log(this, &quot;https:\/\/www.youtube.com\/watch?v=9s2zNZydiI&quot;, and so on ....... "> 
</description>

Android Parser Code:

Element imgElement = docHtml.select("a").first();
                    if (imgElement != null) {


                        IDContent = imgElement2.attr("onclick");

                    }

问题:

如何在“watch?v =”和“;”之间获取Youtube ID

1 个答案:

答案 0 :(得分:0)

使用URLDecoder解码网址字符串。

然后使用正则表达式从url

中提取VideoID
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;
}