Android Jsoup 从所选元素获取 YouTube 视频 ID
Android Jsoup get a YouTubeVideo ID form an selected Element
RSS 字符串:
<description>
<a href="https://www.facebook.com/l.php?u=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%39s2zWNZydiI&h=aAQEbhn3&s=1" id="" title="" target="" onclick="LinkshimAsyncLink.referrer_log(this, "https:\/\/www.youtube.com\/watch?v=9s2zNZydiI", and so on ....... ">
</description>
Android 解析器代码:
Element imgElement = docHtml.select("a").first();
if (imgElement != null) {
IDContent = imgElement2.attr("onclick");
}
问题:
如何获取 "watch?v=" 和“;”之间的 Youtube ID
使用URLDecoder解码url字符串。
然后使用正则表达式从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;
}
RSS 字符串:
<description>
<a href="https://www.facebook.com/l.php?u=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%39s2zWNZydiI&h=aAQEbhn3&s=1" id="" title="" target="" onclick="LinkshimAsyncLink.referrer_log(this, "https:\/\/www.youtube.com\/watch?v=9s2zNZydiI", and so on ....... ">
</description>
Android 解析器代码:
Element imgElement = docHtml.select("a").first();
if (imgElement != null) {
IDContent = imgElement2.attr("onclick");
}
问题:
如何获取 "watch?v=" 和“;”之间的 Youtube ID
使用URLDecoder解码url字符串。
然后使用正则表达式从url
中提取VideoIDpublic 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;
}