在 Dart/Flutter 中使用正则表达式从文档中获取 YouTube 网址
Get YouTube URLs from a document using Regex in Dart/Flutter
我看到了一些 Whosebug
这个问题的答案,但他们都使用了 JavaScript
问题是:- 如何在 Dart/Flutter
中使用正则表达式从文档中获取 YouTube URLs
我有一个来自我的后端的文档,它有 HTML
个标签,并且里面有一个嵌入的 YouTube
视频。但最终,它就像一个文本文档,不是吗?
首先这是我的文档,我想从
获取 YouTube
link
<figure
class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-4-3 wp-has-aspect-ratio">
<div class="wp-block-embed__wrapper">
<iframe
title="| Title here |"
width="1170"
height="878"
src="https://www.youtube.com/embed/OWGnQ61kLzw?feature=oembed" // <-- I want to get this link
frameborder="0"
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
allowfullscreen
></iframe>
</div>
</figure>
这是我用来获取这个的 Dart
代码,但我失败了
String getYouTubeUrl(String content) {
RegExp regExp = RegExp(
r'^((?:https?:)?\/\/)?((?:www|m)\.)?((?:youtube\.com|youtu.be))(\/(?:[\w\-]+\?v=|embed\/|v\/)?)([\w\-]+)(\S+)?$');
String matches = regExp.stringMatch(content);
if (matches == null) {
return ''; // Always returns here while the video URL is in the content paramter
}
final String youTubeUrl = matches;
return youTubeUrl;
}
我做错了什么吗?我的 RegExp
正确吗?这是我想要的:- https://regexr.com/3dj5t
根据提到的网站,RegExp
实际上是正确的,但在 Dart 中我似乎无法让它工作
现在,如何从该文档中提取 YouTube URL?
试试这个:
((?:https?:)?\/\/)?((?:www|m)\.)?((?:youtube\.com|youtu.be))(\/(?:[\w\-]+\?v=|embed\/|v\/)?)([\w\-]+)(\S+)?
解释:
在您的文档中,youtube link 不在行首,也不在行尾结束,因此 ^ 和 $ 是不必要的
我看到了一些 Whosebug
这个问题的答案,但他们都使用了 JavaScript
问题是:- 如何在 Dart/Flutter
中使用正则表达式从文档中获取 YouTube URLs我有一个来自我的后端的文档,它有 HTML
个标签,并且里面有一个嵌入的 YouTube
视频。但最终,它就像一个文本文档,不是吗?
首先这是我的文档,我想从
获取YouTube
link
<figure
class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-4-3 wp-has-aspect-ratio">
<div class="wp-block-embed__wrapper">
<iframe
title="| Title here |"
width="1170"
height="878"
src="https://www.youtube.com/embed/OWGnQ61kLzw?feature=oembed" // <-- I want to get this link
frameborder="0"
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
allowfullscreen
></iframe>
</div>
</figure>
这是我用来获取这个的 Dart
代码,但我失败了
String getYouTubeUrl(String content) {
RegExp regExp = RegExp(
r'^((?:https?:)?\/\/)?((?:www|m)\.)?((?:youtube\.com|youtu.be))(\/(?:[\w\-]+\?v=|embed\/|v\/)?)([\w\-]+)(\S+)?$');
String matches = regExp.stringMatch(content);
if (matches == null) {
return ''; // Always returns here while the video URL is in the content paramter
}
final String youTubeUrl = matches;
return youTubeUrl;
}
我做错了什么吗?我的 RegExp
正确吗?这是我想要的:- https://regexr.com/3dj5t
根据提到的网站,RegExp
实际上是正确的,但在 Dart 中我似乎无法让它工作
现在,如何从该文档中提取 YouTube URL?
试试这个:
((?:https?:)?\/\/)?((?:www|m)\.)?((?:youtube\.com|youtu.be))(\/(?:[\w\-]+\?v=|embed\/|v\/)?)([\w\-]+)(\S+)?
解释:
在您的文档中,youtube link 不在行首,也不在行尾结束,因此 ^ 和 $ 是不必要的