【问题标题】:Get url src from iframe using regex c#使用正则表达式 c# 从 iframe 获取 url src
【发布时间】:2014-03-14 11:28:51
【问题描述】:

我正在尝试从 iframe 获取 soundcloud 播放列表 ID,但在 c# 中,iframe 标签会创建转义示例:

"<iframe width=\"100%\" height=\"450\" scrolling=\"no\" frameborder=\"no\" src=\"https://w.soundcloud.com/player/?url=https%3A//api.soundcloud.com/playlists/26104012&amp;auto_play=false&amp;hide_related=false&amp;visual=true%22\"></iframe>"

如何使用带有此 iframe 标签的正则表达式获取播放列表 ID? 这是 ID 26104012

【问题讨论】:

    标签: c# regex soundcloud


    【解决方案1】:

    如果 id 始终为 8 位,请尝试以下操作:

    string text = "<iframe width=\"100%\" height=\"450\" scrolling=\"no\" frameborder=\"no\" src=\"https://w.soundcloud.com/player/?url=https%3A//api.soundcloud.com/playlists/26104012&amp;auto_play=false&amp;hide_related=false&amp;visual=true%22\"></iframe>";
    Regex r = new Regex(@"\d{8}");
    string result = r.Match(text).Value;
    

    或者如果它总是在网址的第一部分,使用这个:

    string text = "<iframe width=\"100%\" height=\"450\" scrolling=\"no\" frameborder=\"no\" src=\"https://w.soundcloud.com/player/?url=https%3A//api.soundcloud.com/playlists/26104012&amp;auto_play=false&amp;hide_related=false&amp;visual=true%22\"></iframe>";
    Regex r = new Regex(@"\d+&");
    string t = r.Match(text).Value.Replace("&", "");
    

    【讨论】:

      【解决方案2】:

      你可以使用这个正则表达式:

      playlists/+([\d]+)
      

      【讨论】:

        【解决方案3】:

        您可以使用以下代码匹配该号码:

        string search = "<iframe width=\"100%\" height=\"450\" scrolling=\"no\" frameborder=\"no\" src=\"https://w.soundcloud.com/player/?url=https%3A//api.soundcloud.com/playlists/26104012&amp;auto_play=false&amp;hide_related=false&amp;visual=true%22\"></iframe>";
        string sPattern = "^.*src=.*playlists\\/([0-9]+)&.*$";
        
        
        Match match = Regex.Match(search, sPattern, RegexOptions.IgnoreCase);
        // Here we check the Match instance.
        if (match.Success)
        {
            // Finally, we get the Group value and display it.
            string id = match.Groups[1].Value;
        }
        

        【讨论】:

          【解决方案4】:

          我知道您想使用 Regex 来解析 HTML,但根据我的经验,这绝不是一个好主意,HTML 通常太可变,Regex 不可靠。如果我是你,我会使用像 htmlagilitypack 这样的 HTML 解析器。

          【讨论】:

          • 我没有得到 html,只是这里的 soundcloudid html 是可变的,但是我检查的上面的正则表达式更可靠,因为它获得了播放列表源
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-05-20
          • 2022-11-18
          相关资源
          最近更新 更多