Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Html Regex(Ruby)用于捕获对象名称和id号_Html_Ruby_Regex - Fatal编程技术网

Html Regex(Ruby)用于捕获对象名称和id号

Html Regex(Ruby)用于捕获对象名称和id号,html,ruby,regex,Html,Ruby,Regex,例如,我有两个潜在的加价: <iframe src="http://embed.app.com/packages/495" width="850" height="480" frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe> <iframe src="https://embed.app.com/videos/10332?hide_text=1&

例如,我有两个潜在的加价:

<iframe src="http://embed.app.com/packages/495" width="850" height="480" frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe>

<iframe src="https://embed.app.com/videos/10332?hide_text=1&amp;buy_btn=0&amp;autoplay=0" width="960" height="540" class="responsive-embed"></iframe>
我希望使用Ruby match,无论是视频还是软件包,以及它的:id号


非常感谢您的帮助

仅在使用XML解析器后使用regex。否则

只要获得src属性,就可以使用以下快速正则表达式解析链接:

https?:\/\/embed\.app\.com\/((?:packages)|(?:videos))\/([0-9]+)
然后,您将在第一个捕获组中获得软件包或视频,您可以根据自己的喜好修剪s。在第二个捕获组中,您将获得id

有关示例,请参见此处:

试试这个。看演示


nokogiri在iframe标记中查找src属性的示例和提取信息的模式:

require 'nokogiri'

html_doc = <<EOD
<iframe src="http://embed.app.com/packages/495" width="850" height="480" frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe>
<iframe src="https://embed.app.com/videos/10332?hide_text=1&amp;buy_btn=0&amp;autoplay=0" width="960" height="540" class="responsive-embed"></iframe>
EOD

puts "Type         ID\n----------------------"
doc = Nokogiri::HTML.parse(html_doc)
srcList = doc.xpath('//iframe/@src')
srcList.each do |src| 
    if ( m = src.to_s.match(/\/(?<type>packages|videos)\/(?<id>[0-9]+)/) )
        printf("%-12s %s\n",m[:type], m[:id])
    end
end
在ruby中,Regex是

/iframe src="http:\/\/[^\/]+\/[packages|videos]+\/([^"]+)"/
Ruby 2.0支持\K。因此您可以使用下面的正则表达式

<iframe src="https?:\/\/[^\s]*?\/\K(?:videos|packages)\/\d+

如果您不想匹配id,请使用此

<iframe src="https?:\/\/[^\s]*?\/\K(?:videos|packages)

这将在两个单独的组中捕获两者

<iframe src="https?:\/\/[^\s]*?\/\K(videos|packages)\/(\d+)

正则表达式是用什么编程语言编写的?只有在使用XML解析器后才使用正则表达式。否则:id表示495和10332@han058是的。thanks@chhhris你是说这个吗?如果你已经使用了XML解析器,那么为什么不加入URI或Addressable来解析URL呢?@muistooshort他们要求使用正则表达式,所以我给了他们正则表达式。这可能是一个更好的选择,尽管到目前为止,这与身份证号码相匹配。。。如果我不知道我正在解析哪个html,我如何匹配它是视频还是软件包?对不起,我在regex很糟糕,而且还有最后期限。谢谢@chhhris也可以添加它们。?=包|视频|视频|包,您已经准备好滚动感谢@vks,澄清一下,我的意思是在两个示例标记之间,我如何使匹配值等于包或视频而不是:id。例如,我得到了以下结果:@chhris没有得到你。你已经有了视频和包的匹配项。你想要两个视频id吗?@chhris Try^.*.\/?=packages?| videos?*.\/\d+最后一个正是我要找的!
<iframe src="https?:\/\/[^\s]*?\/\K(videos|packages)\/(\d+)