Flutter Dart:如何从视频 URL 中提取 youtube 视频 ID?

Sha*_*ram 3 regex dart flutter

如何使用 dart regex 从视频 URL 中提取 YouTube 视频 ID?

示例网址

https://www.youtube.com/watch?v=SEkUienM2oY&t=1265s
Run Code Online (Sandbox Code Playgroud)

或者

https://m.youtube.com/watch?v=SEkUienM2oY&t=1265s
Run Code Online (Sandbox Code Playgroud)

返回

SEkUienM2oY&t=1265s
Run Code Online (Sandbox Code Playgroud)

它为我工作

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

但是如何用正则表达式做到这一点?

Emm*_*mma 5

如果我们所有的 URL 都与问题中的输入字符串相似,我们可以简单地使用类似于以下的表达式提取这些 ID:

.*\?v=(.+?)&.+
Run Code Online (Sandbox Code Playgroud)

我们想要的输出在这个捕获组中:(.+?)

演示

参考

该 ID似乎有11 个字母数字字符。[A-Za-z0-9]{11}如果您想设计复杂的表达式,这可能是独一无二的:

  • 不适用于 https://youtu.be/S5ZjEtC2aNo (2认同)

Pra*_*ath 5

没有正则表达式,我希望这能完美运行 将此依赖项添加到您的 pubspec.yaml 文件中

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

          }
Run Code Online (Sandbox Code Playgroud)