假设我们有以下字符串数组(这个数组要大得多):
[
'http://www.example.com?id=123456',
'http://www.example.com?id=234567'
]
如您所见,两个字符串中直到第一个数字的所有内容都是相同的。有没有办法轻松找到两个字符串的共同点和不同点?这样我就得到了像 'http://www.example.com?id='
这样的字符串和像 ['123456', '234567']
这样的数组。
最佳答案
这是一种在数组中查找最长公共(public)前缀的方法。
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"
关于ruby - 使用 Regexp 在 Ruby 中匹配模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25425880/