I want to check if an url is valid youtube url so that I can shown in view otherwise I will hide the view.
Is there any regular expression in Java that can help me to check if url is valid. Currently I am using this regex but I guess it's not the one I want:
String youTubeURl = "https://www.youtube.com/watch?v=Btr8uOU0BkI";
String pattern = "https?:\\/\\/(?:[0-9A-Z-]+\\.)?(?:youtu\\.be\\/|youtube\\.com\\S*[^\\w\\-\\s])([\\w\\-]{11})(?=[^\\w\\-]|$)(?![?=&+%\\w]*(?:['\"][^<>]*>|<\\/a>))[?=&+%\\w]*";
if (!youTubeURl.isEmpty() && youTubeURl.matches(pattern)) {
/// Valid youtube URL
}
else{
// Not Valid youtube URL
}
In order to achieve what you want you should use this Regex like so:
where
youtubeUrl
can be any URL of the following list:This regex can match any types of URLs related to youtube.com
This works for me.
If you want to retrieve the Youtube videoId you can use the following function.
You should use
It will return True if URL is valid and false if URL is invalid.
This doesn't check if URL is valid or not. It only checks for strings "youtube" & "youtu.be" in your URL. Following is the regex
" .* " at beginning & end means that there could be anything on left & right of the expression(youtube & youtu.be) you are checking.
NOTE: This has nothing to do with the validity of the URL
Use android.webkit.URLUtil.isValidUrl(java.lang.String) to check if url is valid. And then you can check if url contains Youtube string.
Like