How to Extract YouTube Video IDs from Text Using Regular Expressions
Problem:
Given a text field where users can enter text, the task is to extract all YouTube video URLs and their corresponding IDs.
Solution using Regular Expressions:
To extract YouTube video IDs from a given string, you can use a regular expression that can match all possible YouTube URL formats. Here's a sample regex that can achieve this:
https?://(?:[0-9A-Z-]+\.)?(?:youtu.be/|youtube(?:-nocookie)?\.com\S*?[^\w\s-])([\w-]{11})(?=[^\w-]|$)(?![?=&+%\w.-]*(?:['"][^<>]*>|</a>))[?=&+%\w.-]*
Regex Breakdown:
Usage:
You can use this regex with any programming language that supports regular expressions. For example, in JavaScript, you can use the following code to extract YouTube video IDs:
function extractYouTubeIds(text) { const regex = /https?://(?:[0-9A-Z-]+\.)?(?:youtu.be/|youtube(?:-nocookie)?.com\S*?[^\w\s-])([\w-]{11})(?=[^\w-]|$)(?![?=&+%\w.-]*(?:['"][^<>]*>|</a>))[?=&+%\w.-]*/; const matches = text.match(regex); return matches ? matches.map(id => id.slice(17)) : []; }
Note that the slice(17) removes the "https://www.youtube.com/watch?v=" prefix from the YouTube URL to extract the video ID.
The above is the detailed content of How to Extract YouTube Video IDs from Text Using Regular Expressions?. For more information, please follow other related articles on the PHP Chinese website!