How to get youtube video id from URL with java?

前端 未结 6 2022
伪装坚强ぢ
伪装坚强ぢ 2020-12-16 06:51

I want to get the v=id from youtube\'s URL with java

Example Youtube URL formats:

http://www.youtube.com/watch?v=u8nQa1cJyX8&

6条回答
  •  没有蜡笔的小新
    2020-12-16 07:54

    Try this code here.

    // (?:youtube(?:-nocookie)?\.com\/(?:[^\/\n\s]+\/\S+\/|(?:v|e(?:mbed)?)\/|\S*?[?&]v=)|youtu\.be\/)([a-zA-Z0-9_-]{11})
    final static String reg = "(?:youtube(?:-nocookie)?\\.com\\/(?:[^\\/\\n\\s]+\\/\\S+\\/|(?:v|e(?:mbed)?)\\/|\\S*?[?&]v=)|youtu\\.be\\/)([a-zA-Z0-9_-]{11})";
    
    public static String getVideoId(String videoUrl) {
        if (videoUrl == null || videoUrl.trim().length() <= 0)
            return null;
    
        Pattern pattern = Pattern.compile(reg, Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(videoUrl);
    
        if (matcher.find())
            return matcher.group(1);
        return null;
    }
    

    You can find my whole parser code from here https://github.com/TheFinestArtist/YouTubePlayerActivity/blob/master/library/src/main/java/com/thefinestartist/ytpa/utils/YoutubeUrlParser.java

    This is useful open source I made to play Youtube Video. https://github.com/TheFinestArtist/YouTubePlayerActivity

提交回复
热议问题