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
  • 2,106
  • 17
  • 40

5 Answers5

4

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

          }
Prasath
  • 893
  • 1
  • 8
  • 27
3

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
  • 1
  • 9
  • 28
  • 53
1

Such Regex can parse Youtube video Urls without timing as well

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

Complete example in dart:

 final regex = RegExp(r'.*\?v=(.+?)($|[\&])', caseSensitive: false, multiLine: false);
  final url = [PASTE_YOUTUBE_URL_HERE];
  if (regex.hasMatch(text)) {
    final videoId = regex.firstMatch(text).group(1);
    print(videoId);
  } else {
    print("Cannot parse $url");
  }
Sirelon
  • 4,236
  • 3
  • 17
  • 26
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
  • 869
  • 1
  • 6
  • 21
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
  • 14,668
  • 7
  • 90
  • 90