【问题标题】:How can I filter out URIs that match a scheme?如何过滤掉与方案匹配的 URI?
【发布时间】:2017-07-12 17:41:45
【问题描述】:

这是 Ruby on Rails 应用程序的 ActiveJob/

我正在使用 Anemone 网络爬虫,并在 www.example.com 的主页上创建了所有 URI 的数组。我想过滤掉那些没有特定路径的。

所以www.example.com/somepath 应该被选中并保存,而www.example.com/someotherpath 不应该被选中并保存。

问题是我不能不过滤这些数组条目。没有可用于它们的正则表达式方法。

我在顶部需要 'uri',但仍然收到 method does not exist 错误。

【问题讨论】:

    标签: ruby-on-rails ruby uri


    【解决方案1】:

    使用数组的select 和字符串的include 来完成这项艰巨的工作。

    your_array = [ URI('www.example.com/somepath'),
                   URI('www.example.com/someotherpath') ]
    filter = 'somepath'
    
    your_array.select { |t| t.to_s.include?(filter) }
    
    => [URI("www.example.com/somepath")]
    

    【讨论】:

    • 我会试一试,但我不相信 URI 是字符串,它们是 URI 对象。字符串方法对它们不起作用。
    • 我会更新代码,虽然看起来 URI 可以使用 .to_s,这无论如何都不会损害字符串。
    • 我正在考虑使用它,但 Anemone 有一个用于 CookieStore 对象的 .to_s 方法,所以我不确定它是否能正确执行。
    • 很高兴,确实如此。 :)
    • 我无法让它工作,所以我查看了文档中的 select 方法,并想改用 .select! 方法。它编辑它被调用的数组,而.select 产生一个新数组。
    【解决方案2】:

    下面的正则表达式会为你工作。

    http:\/\/example\.com\/somepath($|\/.*)
    

    编写一个 ruby​​ 代码来检查字符串是否匹配这个正则表达式,然后你就完成了。

    类似的东西:

    def right_string(string)
      string.match(http:\/\/example\.com\/somepath($|\/.*)) ## this return true / false
    end
    

    【讨论】:

      猜你喜欢
      • 2020-09-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多