Ruby与Regexp中的匹配模式

时间:2014-08-21 12:02:50

标签: ruby regex

假设我们有以下字符串数组(此数组更大):

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

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

2 个答案:

答案 0 :(得分:2)

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

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"

答案 1 :(得分:0)

# 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
相关问题