Check if URL is valid YouTube video URL or not in Java

In this tutorial, we will learn if the URL is a valid YouTube video URL or not in Java.

Youtube URL contains a pattern.

We are given a String and we check if a String given contains Youtube URL pattern. If it contains a pattern, the URL is a valid Youtube URL.

We create a function “isYoutubeUrl” which takes one String Parameter. This function returns a boolean value. if the String is empty or it matches the pattern, it returns true else it returns false. The code is given below:

 public class URLValid {
  
  public static boolean isYoutubeUrl(String youTubeURl)
  {
         boolean success;
         String check = "^(http(s)?:\\/\\/)?((w){3}.)?youtu(be|.be)?(\\.com)?\\/.+";
         if (!youTubeURl.isEmpty() && youTubeURl.matches(check))
         {
             success = true;
         }
         else
         {
             
             success = false;
         }
         return success;
    }

    public static void main(String[] args) 
    { 
        String url1 = "https://www.youtube.com/watch?v=F89J_IfAfiE"; 
        if (isYoutubeUrl(url1))  
            System.out.println("Yes"); 
        else
            System.out.println("No");      
              
        String url2 = "https://www.codespeedy.com"; 
        if (isYoutubeUrl(url2))  
            System.out.println("Yes"); 
        else
            System.out.println("No");                 
    } 

}

Summary:

isyouTubeURL is a function whose return type is boolean. It takes one parameter which is a String. That String is analyzed for a valid YouTube URL.

Also read, Validate an IP address using Regular Expressions in Java

Leave a Reply

Your email address will not be published. Required fields are marked *