簡體   English   中英

Ruby與Regexp中的匹配模式

[英]Match pattern in Ruby with Regexp

讓我們說我們有以下字符串數組(這個數組更大):

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

如您所見,直到第一個數字的所有內容在兩個字符串中都是相同的。 有沒有辦法輕松找到兩個字符串的共同點和不同之處? 所以我得到一個像'http://www.example.com?id='這樣的字符串和像'http://www.example.com?id=' ['123456', '234567']這樣的數組。

這是一種在數組中查找最長公共前綴的方法。

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"
# 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM