【问题标题】:Match pattern in Ruby with Regexp使用正则表达式匹配 Ruby 中的模式
【发布时间】:2014-08-21 12:02:49
【问题描述】:

假设我们有以下字符串数组(这个数组要大得多):

[
  'http://www.example.com?id=123456',
  'http://www.example.com?id=234567'
]

如您所见,两个字符串中直到第一个数字的所有内容都是相同的。有没有办法轻松找到两个字符串的共同点和不同点?这样我就会得到一个像'http://www.example.com?id=' 这样的字符串和像['123456', '234567'] 这样的数组。

【问题讨论】:

  • ['http://www.example.com?id=123456', 'http://www.example.com?id=123457'] 会发生什么?
  • Regexp 可能不是解决此问题的理想工具。构建一个 trie 很简单,不会很慢,并且可以解决您的问题。
  • 它应该输出(如问题中所述)'example.com?id=',因为这两个字符串有共同点。
  • @Taemyr 你能举个例子说明你会怎么做吗?
  • @Severin 从未使用 Ruby 编程。 stackoverflow.com/questions/9042426/… 讨论过它,但答案调用了我不熟悉的命令,所以我不能保证它的功能。 Trie 是一种常见的数据结构,因此可以在 Google 上搜索。 - 另请注意,这对您的问题来说有点矫枉过正。

标签: ruby regex


【解决方案1】:

这是一种在数组中查找最长公共前缀的方法。

def _lcp(str1, str2)
  end_index = [str1.length, str2.length].min - 1
  end_index.downto(0) do |i|
    return str1[0..i] if str1[0..i] == str2[0..i]
  end
  ''
end

def lcp(strings)
  strings.inject do |acc, str|
    _lcp(acc, str)
  end
end


lcp [
  'http://www.example.com?id=123456',
  'http://www.example.com?id=234567',
  'http://www.example.com?id=987654'
]
#=> "http://www.example.com?id="

lcp [
  'http://www.example.com?id=123456',
  'http://www.example.com?id=123457'
]
#=> "http://www.example.com?id=12345"

【讨论】:

  • 谢谢,正是我想要的!
  • 编辑:将max更改为min,因为最长的前缀只能与较短的字符串一样长。
【解决方案2】:
# This is an approach using higher level ruby std-lib components instead of a regex.
# Why re-invent the wheel?
module UriHelper
    require 'uri'
    require 'cgi'

    # Take an array of urls and extract the id parameter.
    # @param urls {Array} an array of urls to parse
    # @returns {Array}
    def UriHelper.get_id_params( urls )
        urls.map do |u| 
            puts u
            uri = URI(u)
            params = CGI::parse(uri.query)  
            params["id"].first # returned
        end
    end
end

require "test/unit"
# This is unit test proving our helper works as intended
class TestUriHelper < Test::Unit::TestCase
  def test_get_id_params
    urls = [
        'http://www.example.com?id=123456',
        'http://www.example.com?id=234567'
    ]
    assert_equal("123456", UriHelper.get_id_params(urls).first )
    assert_equal("234567", UriHelper.get_id_params(urls).last )
  end
end

【讨论】:

    猜你喜欢
    • 2020-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-25
    相关资源
    最近更新 更多