3

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??

Shahzad Akram
  • 3,340
  • 2
  • 25
  • 56

6 Answers6

8

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";

}
Ruli
  • 2,403
  • 12
  • 27
  • 35
Prasath
  • 1,374
  • 4
  • 13
  • 38
5

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:

Emma
  • 26,487
  • 10
  • 35
  • 65
1

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;
    }
  }
Sirelon
  • 5,468
  • 4
  • 23
  • 29
1
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;
}
Andrey Ozornin
  • 987
  • 1
  • 8
  • 22
1

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

Paresh Mangukiya
  • 37,512
  • 17
  • 201
  • 182
0
static String? convertUrlToId(String url, {bool trimWhitespaces = true}) {
    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;
}
Ruli
  • 2,403
  • 12
  • 27
  • 35
  • 1
    Please add an explanation of how and why this solves the problem. Also it seems very similar to solution by @shanu12joshi. It would be good to describe how it differs. – Ruli Sep 08 '21 at 07:19