Flutter Dart : How to extract youtube video ID from video URL?

4,276

Solution 1

If all our URLs are similar to our input string in the question, we can simply just extract those IDs with an expression similar to:

.*\?v=(.+?)&.+

and our desired output is in this capturing group: (.+?)

Demo

Reference

It seems we'd have 11 alphanumeric chars [A-Za-z0-9]{11} for that ID. That might be something unique if you'd want to design sophisticated expressions:

Solution 2

Without regex, I hope this will work perfectly Add this dependency into your pubspec.yaml file

youtube_player_flutter: ^6.1.0+4

try {

    videoIdd = YoutubePlayer.convertUrlToId("your url here");
    print('this is '+videoId);

  } on Exception catch (exception) {

    // only executed if error is of type Exception
    print('exception');

  } catch (error) {

    // executed for errors of all types other than Exception
     print('catch error');
   //  videoIdd="error";

}

Solution 3

Such Regex can parse Youtube video Urls without timing as well

.*\?v=(.+?)($|[\&])

Complete example in dart:

  String? _getYoutubeVideoIdByURL (String url) {
    final regex = RegExp(r'.*\?v=(.+?)($|[\&])', caseSensitive: false);

    try {
      if (regex.hasMatch(url)) {
        return regex.firstMatch(url)!.group(1);
      }
    } catch (e) {
      return null;
    }
  }

Solution 4

static String convertUrlToId(String url, {bool trimWhitespaces = true}) {
  assert(url?.isNotEmpty ?? false, 'Url cannot be empty');
  if (!url.contains("http") && (url.length == 11)) return url;
  if (trimWhitespaces) url = url.trim();

  for (var exp in [
    RegExp(
        r"^https:\/\/(?:www\.|m\.)?youtube\.com\/watch\?v=([_\-a-zA-Z0-9]{11}).*$"),
    RegExp(
        r"^https:\/\/(?:www\.|m\.)?youtube(?:-nocookie)?\.com\/embed\/([_\-a-zA-Z0-9]{11}).*$"),
    RegExp(r"^https:\/\/youtu\.be\/([_\-a-zA-Z0-9]{11}).*$")
  ]) {
    Match match = exp.firstMatch(url);
    if (match != null && match.groupCount >= 1) return match.group(1);
  }

  return null;
}

Solution 5

There is a package on the pub to get id youtube_parser

youtube_parser minimalist library that extracts IDs from all kinds of YouTube URLs

import 'package:youtube_parser/youtube_parser.dart';

String foo = getIdFromUrl('https://www.youtube.com/watch?v=CBWlfU_na-2');
// returns 'CBWlfU_na-2'

String bar = getIdFromUrl('https://www.notyoutube.com/watch?v=CBWlfU_na-2');
// returns null

That's also what the Uri.parse is ultimately using now

Share:
4,276
Shahzad Akram
Author by

Shahzad Akram

Updated on December 11, 2022

Comments

  • Shahzad Akram
    Shahzad Akram over 1 year

    How to use dart regex to extract YouTube video ID from video URL?

    Example URL

    https://www.youtube.com/watch?v=SEkUienM2oY&t=1265s
    

    or

    https://m.youtube.com/watch?v=SEkUienM2oY&t=1265s
    

    Return

    SEkUienM2oY&t=1265s
    

    Its working for me

      String getVideoID(String url) {
        url = url.replaceAll("https://www.youtube.com/watch?v=", "");
        url = url.replaceAll("https://m.youtube.com/watch?v=", "");
        return url;
      }
    

    but how to do this with Regex??