I want to get the v=id from youtube\'s URL with java
Example Youtube URL formats:
http://www.youtube.com/watch?v=u8nQa1cJyX8&
You can use regex I've created:
public static String YOUTUBE_PATTERN_ID = "^(?:(?:\\w*.?://)?\\w*.?\\w*-?.?\\w*/(?:embed|e|v|watch|.*/)?\\??(?:feature=\\w*\\.?\\w*)?&?(?:v=)?/?)([\\w\\d_-]+).*";
Pattern matcher = Pattern.compile(YOUTUBE_PATTERN_ID).matcher(url)
if (matcher.find()) {
return matcher.group(1)
}
https://regex101.com/r/b0yMMd/1
Used snippet base from this answer: https://stackoverflow.com/a/35436389/7138308
var regex = /^(?:(?:\w*.?:\/\/)?\w*.?\w*\-?.?\w*\/(?:embed|e|v|watch|.*\/)?\??(?:feature=\w*\.?\w*)?\&?(?:v=)?\/?)([\w\d_-]+).*/i;
// An array of all the youtube URLs
var youtubeLinks = [
'http://www.youtube.com/watch?v=u8nQa1cJyX8&a=GxdCwVVULXctT2lYDEPllDR0LRTutYfW ',
'http://www.youtube.com/watch?v=u8nQa1cJyX-8 ',
'http://youtu.be/0zM3nApSvMg ',
'http://www.youtube.com/user/IngridMichaelsonVEVO#p/a/u/1/KdwsulMb8EQ ',
'http://youtu.be/dQw4w9WgXcQ ',
'http://www.youtube.com/embed/dQw4w9WgXcQ ',
'http://www.youtube.com/v/dQw4w9WgXcQ ',
'http://www.youtube.com/e/dQw4w9WgXcQ ',
'http://www.youtube.com/watch?v=dQw4w9WgXcQ ',
'http://www.youtube.com/?v=dQw4w9WgXcQ ',
'http://www.youtube.com/watch?feature=player_embedded&v=dQw4w9WgXcQ ',
'http://www.youtube.com/?feature=player_embedded&v=dQw4w9WgXcQ ',
'http://www.youtube.com/user/IngridMichaelsonVEVO#p/u/11/KdwsulMb8EQ ',
'http://www.youtube-nocookie.com/v/6L3ZvIMwZFM?version=3&hl=en_US&rel=0 ',
'https://m.youtube.com/watch?feature=youtu.be&v=ROkXM3csNWY ',
'https://www.youtube.com/watch?v=rie69P0W668 ',
'https://m.youtube.com/watch?feature=youtu.be&v=JqyzwbpYYqc ',
'https://www.youtube.com/watch?v=YPln3JP_gKs&feature=youtu.be ',
'https://www.youtube.com/watch?v=l-kX8Z4u0Kw&list=PLhml-dmiPOedRDLV8n1ro_OTdzKjOdlyp'
];
// An object to store the results
var youtubeIds = {};
// Iterate over the youtube URLs
youtubeLinks.forEach(function(url) {
// Get the value of second captured group to extract youtube ID
var id = "" + (url.match(regex) || [0, 0, 'No ID present'])[1] + "";
// Add the URL and the extracted ID in the result object
youtubeIds[url] = id;
});
// Log the object in the browser console
console.log(youtubeIds);
// To show the result on the page
document.getElementById('output').innerHTML = JSON.stringify(youtubeIds, 0, 4);
.youtubeId {
color: green;
font-weight: bold;
}