Reputation: 57129
I have the following string for example:
abcba"c"bacba"fbaf"gdsfgafa"http://www.youtube.com/watch?v=0eLoApO7wrs"gsg
How can I extract the youtube url from this string?
Upvotes: 1
Views: 920
Reputation: 39
If you'd like to cover all YouTube URL variants try this:
\"(?:(?:https?:)?\/\/)?(?:(?:(?:www|m(?:usic)?)\.)?youtu(?:\.be|be\.com)\/(?:shorts\/|live\/|v\/|e(?:mbed)?\/|watch(?:\/|\?(?:\S+=\S+&)*v=)|oembed\?url=https?%3A\/\/(?:www|m(?:usic)?)\.youtube\.com\/watch\?(?:\S+=\S+&)*v%3D|attribution_link\?(?:\S+=\S+&)*u=(?:\/|%2F)watch(?:\?|%3F)v(?:=|%3D))?|www\.youtube-nocookie\.com\/embed\/)([\w-]{11})[\?&#]?\S*\"
It's a RegExp from a related question for any known YouTube URL (also music.*, shorts/, live/, e/ embed/, v/, *-nocookie etc.). Also catches video ID.
If you want you can restrict the video ID further with Glenn's answer instead of ([\w-]{11})
.
Upvotes: 0
Reputation: 31
var id = Regex.Match(html,@"(?:youtube\.com\/(?:[^\/]+\/.+\/|(?:v|e(?:mbed)?
\/|.*[?&]v=)|youtu\.be\/)([^""&?\/ ]{11})").Groups[1].Value;
Upvotes: 1