Search code examples
androidregexurlyoutubevimeo

Regex for Youtube and Vimoe url


I wanted to validate the url pasted by user for Youtube & Vimeo

Eg:

m.youtube.com, youtu.be, youtube.com, vimeo.com

Also wanted to extract the video id's from them

My code :

if (link.contains("youtu")) {
    String youtubeRegex = "^(http(s)??\\:\\/\\/)?((www\\.)|(m\\.))?((youtube\\.com\\/watch\\?v=)|(youtu.be\\/))([a-zA-Z0-9\\-_])+";
    Pattern pattern = Pattern.compile(youtubeRegex);
    Matcher matcher = pattern.matcher(link);
    if (matcher.find()) {
        isValid = true;
    } else {
        isValid = false;
    }
} else if (link.contains("vimeo")) {
    String vimeoRegex = "^https:\\/\\/?vimeo\\.com\\/(clip\\:)?(\\d+).*$";
    Pattern pattern = Pattern.compile(vimeoRegex);
    Matcher matcher = pattern.matcher(link);
    if (matcher.find()) {
        isValid = true;
    } else {
        isValid = false;
    }
}

This regex doesn't works properly.It accepts even link without https ot http


Solution

  • try my snippet, here youtube url will be validate . if it is valid it will return youtube id otherwise it says, url invalid.

    similarly, it will check vimeo url is valid or not. ( I dont know how vimeo url id looks a like)

    Hope it will work. and i did it using javascript you can run and try the snippet.

    type_1 = "https://www.youtube.com/watch?v=5AaCz_2cZvQ"
    type_2 = "youtu.be/12312/"
    type_3 = "youtube.com"
    type_4 = "vimeo.co"
    get_utube_id_regex = /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=)([^#\&\?]*).*/
    if(get_utube_id_regex.exec(type_1)) {
      console.log("Youtube Video ID type-1 :", get_utube_id_regex.exec(type_1)[2])
    }
    else {
      console.log("invalid Youtube URL in type 1")
    }
    if(get_utube_id_regex.exec(type_2)) {
      console.log("Youtube Video ID type-2 :", get_utube_id_regex.exec(type_2)[2])
    }
    else {
      console.log("invalid Youtube URL in type 2")
    }
    if(get_utube_id_regex.exec(type_3)) {
      console.log("Youtube Video ID type-3 :", get_utube_id_regex.exec(type_3)[2])
    }
    else {
      console.log("invalid Youtube URL in type 3")
    } 
    if(/vimeo.com/.exec(type_4)) {
      console.log(/vimeo.com/.exec(type_4)) 
    }
    else {
      console.log("Invalid Vimeo URL in type 4")
    }