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
  • 4,586
  • 6
  • 32
  • 65

5 Answers5

11

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,592
  • 12
  • 30
  • 40
FGH
  • 2,900
  • 6
  • 26
  • 59
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
  • 27,428
  • 11
  • 44
  • 69
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;
    }
  }
Sirelon
  • 6,446
  • 5
  • 26
  • 30
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
  • 1,129
  • 1
  • 9
  • 24
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,592
  • 12
  • 30
  • 40
  • 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