如何解析 YouTube 网址以使用 Dart 从网址获取视频 ID?



我正在尝试将*这个函数转换为Dart,但到目前为止没有成功。我对正则表达式部分的方式有点困惑。我使用 regExp.allMatches***(url(*** aways 的实现返回了整个 url。

Javascript版本:

function youtube_parser(url){
var regExp = /^.*((youtu.be/)|(v/)|(/u/w/)|(embed/)|(watch?))??v?=?([^#&?]*).*/;
var match = url.match(regExp);
return (match&&match[7].length==11)? match[7] : false;
}

飞镖版:

RegExp regExp = new RegExp(
r'.*(?:(?:youtu.be/|v/|vi/|u/w/|embed/)|(?:(?:watch)??v(?:i)?=|&v(?:i)?=))([^#&?]*).*',
caseSensitive: false,
multiLine: false,
);
final match = regExp.allMatches(url);

谁能帮我?

编辑:

输入网址:

final urls = [
'http://www.youtube.com/watch?v=0zM3nApSvMg&feature=feedrec_grec_index',
'http://www.youtube.com/user/IngridMichaelsonVEVO#p/a/u/1/QdK8U-VIH_o',
'http://www.youtube.com/v/0zM3nApSvMg?fs=1&hl=en_US&rel=0',
'http://www.youtube.com/watch?v=0zM3nApSvMg#t=0m10s',
'http://www.youtube.com/embed/0zM3nApSvMg?rel=0',
'http://www.youtube.com/watch?v=0zM3nApSvMg',
'http://youtu.be/0zM3nApSvMg',
];

每个 getYoutubeVideoId(url( 的输出应该0zM3nApSvMg

提前感谢,

菲 利 普

  • https://stackoverflow.com/a/8260383/564252

好吧,我没有完整的解决方案,但我希望这会对您有所帮助, 您的问题是您正在使用 RegExp,它将结果作为您需要选择的组返回:

final urls = [
'http://www.youtube.com/watch?v=0zM3nApSvMg&feature=feedrec_grec_index',
'http://www.youtube.com/user/IngridMichaelsonVEVO#p/a/u/1/QdK8U-VIH_o',
'http://www.youtube.com/v/0zM3nApSvMg?fs=1&hl=en_US&rel=0',
'http://www.youtube.com/watch?v=0zM3nApSvMg#t=0m10s',
'http://www.youtube.com/embed/0zM3nApSvMg?rel=0',
'http://www.youtube.com/watch?v=0zM3nApSvMg',
'http://youtu.be/0zM3nApSvMg',
];
void main() {
RegExp regExp = new RegExp(
r'.*(?:(?:youtu.be/|v/|vi/|u/w/|embed/)|(?:(?:watch)??v(?:i)?=|&v(?:i)?=))([^#&?]*).*',
caseSensitive: false,
multiLine: false,
);
for (final url in urls) {
final match = regExp.firstMatch(url).group(1); // <- This is the fix
print('$url -> $match');
}
}

此代码将返回:

http://www.youtube.com/watch?v=0zM3nApSvMg&feature=feedrec_grec_index -> 0zM3nApSvMg
http://www.youtube.com/user/IngridMichaelsonVEVO#p/a/u/1/QdK8U-VIH_o -> QdK8U-VIH_o
http://www.youtube.com/v/0zM3nApSvMg?fs=1&amp;hl=en_US&amp;rel=0 -> 0zM3nApSvMg
http://www.youtube.com/watch?v=0zM3nApSvMg#t=0m10s -> 0zM3nApSvMg
http://www.youtube.com/embed/0zM3nApSvMg?rel=0 -> 0zM3nApSvMg
http://www.youtube.com/watch?v=0zM3nApSvMg -> 0zM3nApSvMg
http://youtu.be/0zM3nApSvMg -> 0zM3nApSvMg

如您所见,某些 URL 仍然存在一些问题,但我希望我的解决方案能帮助您使正则表达式正常工作。

最新更新