It doesn't matter, but the language I'm using is kotlin.
my get video Id code
fun getVideoIdFromYoutubeUrl(url: String?): String? {
var videoId: String? = null
val regex =
"(?:https?:\\/\\/)?(?:www\\.)?youtu(?:\\.be\\/|be.com\\/\\S*(?:watch|shorts)(?:(?:(?=\\/[-a-zA-Z0-9_]{11,}(?!\\S))\\/)|(?:\\S*v=|v\\/)))([-a-zA-Z0-9_]{11,})"
// "http(?:s)?:\\/\\/(?:m.)?(?:www\\.)?youtu(?:\\.be\\/|be\\.com\\/(?:watch\\?(?:feature=youtu.be\\&)?v=|v\\/|embed\\/|user\\/(?:[\\w#] \\/) ))([^&#?\\n] )"
val pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE)
val matcher = pattern.matcher(url)
if (matcher.find()) {
videoId = matcher.group(1)
}
return videoId
}
test youtube shots url
https://youtube.com/shorts/IC7M4up0FOI?feature=share
But when I do it with that regular expression, null is returned.
On the other hand, this url works just fine.
https://www.youtube.com/shorts/YK1po3GW9oY
what do i need to fix?
CodePudding user response:
To extract the video ID from a YouTube URL in Kotlin, you can use the following code:
val url = "https://www.youtube.com/watch?v=dQw4w9WgXcQ"
var videoId = ""
if (url.contains("youtube.com")) {
if (url.contains("watch")) {
videoId = url.substring(url.indexOf("v=") 2)
if (videoId.contains("&")) {
videoId = videoId.substring(0, videoId.indexOf("&"))
}
} else if (url.contains("embed")) {
videoId = url.substring(url.lastIndexOf("/") 1)
} else if (url.contains("v/")) {
videoId = url.substring(url.indexOf("v/") 2)
if (videoId.contains("?")) {
videoId = videoId.substring(0, videoId.indexOf("?"))
}
}
}
println("Video ID: $videoId")
CodePudding user response:
How about this?
fun extractVideoId(url: String): String? {
val pattern = "(?<=(v|V)/|(be/)|(?<=embed/)|(?<=watch\\?v=))([\\w-] )"
val matcher = Regex(pattern).toPattern().matcher(url)
return if (matcher.find()) matcher.group() else null
}