我正在尝试将*此函数转换为Dart,到目前为止没有成功。我对正则表达式的组成部分有些困惑。我使用regExp.allMatches ***(url)***的实现返回了整个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;
}
WIP Dart版本:
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
预先感谢
魔咒
答案 0 :(得分:1)
好吧,我没有完整的解决方案,但希望能对您有所帮助,您的问题是您使用的是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&hl=en_US&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仍然存在一些问题,但是我希望我的解决方案能够帮助您使RegExp正常工作。