从flutter中的html提取链接

acruukt9  于 2022-12-09  发布在  Flutter
关注(0)|答案(3)|浏览(149)

我试图从HTML正文中提取一个来自响应的链接。然后消息看起来像这样的“内容”:

{
        "rendered": 
         "<div style=
           "padding: 56.25% 0 0 0; 
            position: relative;">
              <iframe style=
                 "position: absolute; 
                  top: 0; 
                  left: 0; 
                  width: 100%; 
                  height: 100%;" 
                  title="Shrewsberry" 
                  src="https://player.vimeo.com/video/1000224?h=23334&amp;badge=0&amp;autopause=0&amp;player_id=0&amp;app_id=58479\" 
                  frameborder="0" 
                  allowfullscreen="allowfullscreen">
        </iframe>
        </div>"}

我想获取'src=“https://player.vimeo.com/video/1000224?'?'内的内容,有人能帮忙吗?
这是我的代码,我使用它。

final value = parse(html); // html is the value from response
String parsedString = parse(value.body!.text).documentElement!.text;
print(parsedString);

wztqucjr

wztqucjr1#

使用此扩展名

extension StringExtension on String {
  String? extractVideoURL() {
    RegExp regExp = RegExp(
        r"src=(https:\/\/player.vimeo.com\/video\/[0-9]+)",
        caseSensitive: false,
        multiLine: false);
    Iterable<RegExpMatch> matches = regExp.allMatches(this);
    if (matches.isNotEmpty) {
      return matches.first.group(1);
    }
    return null;
  }
}
wbgh16ku

wbgh16ku2#

如果URL始终以?结尾,则可以使用此简单逻辑

void main(){ 
String x='"content": { "rendered": "<div style="padding: 56.25% 0 0 0; position: relative;"><iframe style="position: absolute; top: 0; left: 0; width: 100%; height: 100%;" title="Shrewsberry" **src="https://player.vimeo.com/video/1000224?**h=23334&badge=0&autopause=0&player_id=0&app_id=58479" frameborder="0" allowfullscreen="allowfullscreen">\n"}';
int start= x.indexOf('src');
int end= x.indexOf('?');
print(x.substring(start,end+1));
}
jtjikinw

jtjikinw3#

你可以使用正则表达式从你的原始字符串中提取字符串。考虑到它看起来像HTML,我忽略了你在答案中输入的**。
在这种情况下,正则表达式(?<=src=").*?(?=")应该可以检索源代码。这将适用于任何源代码,而不仅仅是Vimeo。

import 'dart:convert';
void main() {
  String input = "\"content\": { \"rendered\": \"<div style=\"padding: 56.25% 0 0 0; position: relative;\"><iframe style=\"position: absolute; top: 0; left: 0; width: 100%; height: 100%;\" title=\"Shrewsberry\" **src=\"https://player.vimeo.com/video/1000224?\"h=23334&badge=0&autopause=0&player_id=0&app_id=58479\" frameborder=\"0\" allowfullscreen=\"allowfullscreen\">\n\"}";
  
  RegExp regex = new RegExp('(?<=src=").*?(?=")');
  var match = regex.firstMatch(input);
  
  if (match == null) {
    print("No match found.");
    return;
  }
  
  print("Result: " + match.group(0)!);
}

输出:Result: https://player.vimeo.com/video/1000224?

相关问题