-1

I have seen some StackOverflow answers to this question but they all used JavaScript

The question is:- How to get YouTube URLs from a document using Regex in Dart/Flutter

I have a document that comes from my backend and has HTML tags and it has an embedded YouTube video in it. But in the end, it's just like a text document, isn't it?

First here is my document that I want to get the YouTube link from


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


Here is my Dart code that I use to get this but I fail


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

Am I doing something wrong? Is my RegExp correct? Here is what I want:- https://regexr.com/3dj5t

The RegExp is actually correct according to the mentioned website but in Dart I can't seem to get it to work

Now, how can I extract the YouTube URL from this document?

Hussein Al-Mosawi
  • 435
  • 1
  • 7
  • 17
  • use https://pub.dev/packages/html – pskink Nov 04 '20 at 08:37
  • with that package you will be able to get not only src url but also `title` or `width` or `height` by simply calling `iframe['src']` / `iframe['title']` etc – pskink Nov 04 '20 at 09:06
  • @pskink Can you please explain how it works? And make an answer so that I might mark it too. I can't get it to work because it gives me an error iframe['src'] is not a valid selector... Here is how I'm doing it `` Document document = parse(content); print(document.querySelector('iframe["src"]')); `` – Hussein Al-Mosawi Nov 04 '20 at 10:39
  • `var video = doc.getElementsByTagName('iframe')[0]; ` – pskink Nov 04 '20 at 10:40

1 Answers1

0

Try this:

((?:https?:)?\/\/)?((?:www|m)\.)?((?:youtube\.com|youtu.be))(\/(?:[\w\-]+\?v=|embed\/|v\/)?)([\w\-]+)(\S+)?

Regex Demo

Dart Demo

Explanation:

in your document, the youtube link is not at the start of the line and not end exactly at the end of the line so ^ and $ is unnecessary

Alireza
  • 755
  • 1
  • 1
  • 9