我想在数组中搜索某个字符串和(!)其子字符串。例如,我的数组是:
array = ["hello", "hell", "goodbye", "he"]
所以当我搜索“hello”及其子串(但仅从头开始:“he”,“hell”,“hello”)时,它应该返回
=> ["hello", "hell", "he"]
到目前为止我尝试了什么:使用#grep和/或#include的正则表达式?像这样的方法:
array.grep("hello"[/\w+/])
或
array.select {|i| i.include?("hello"[/\w+/])}
但在这两种情况下它只返回
=> ["hello"]
顺便说一下,如果我尝试array.select{|i| i.include?("he")}
它的工作原理,但就像我说的那样,我想要反过来:搜索“你好”并从头开始给我所有结果,包括子串。
答案 0 :(得分:2)
require "abbrev"
arr = ["hello", "hell", "goodbye", "he"]
p arr & ["hello"].abbrev.keys # => ["hello", "hell", "he"]
答案 1 :(得分:1)
array = ["hello", "hell", "goodbye", "he", "he"]
# define search word:
search = "hello"
# find all substrings of this word:
substrings = (0..search.size - 1).each_with_object([]) { |i, subs| subs << search[0..i] }
#=> ["h", "he", "hel", "hell", "hello"]
# find intersection between array and substrings(will exclude duplicates):
p array & substrings
#=> ["hello", "hell", "he"]
# or select array elements that match any substring(will keep duplicates):
p array.select { |elem| substrings.include?(elem) }
#=> ["hello", "hell", "he", "he"]
答案 2 :(得分:1)
将h
中hello
以外的所有字符变为可选字符。
> array = ["hello", "hell", "goodbye", "he"]
> array.select{|i| i[/^he?l?l?o?/]}
=> ["hello", "hell", "he"]
答案 3 :(得分:1)
您仍然可以使用像这样的正则表达式
#define Array
arr = ["hello", "hell", "goodbye", "he"]
#define search term as an Array of it's characters
search = "hello".split(//)
#=> ['h','e','l','l','o']
#deem the first as manditory search.shift
#the rest are optional ['e?','l?','l?','o?'].join
search = search.shift << search.map{|a| "#{a}?"}.join
#=> "he?l?l?o?"
#start at the beginning of the string \A
arr.grep(/\A#{search}/)
#=> ["hello", "hell", "he"]
答案 4 :(得分:1)
正如问题所示:
array.select { |w| "hello" =~ /^#{w}/ }
#=> ["hello", "hell", "he"]
答案 5 :(得分:1)
我使用String#[]
:
array = ["hello", "hell", "goodbye", "he", "he"]
search = "hello"
array.select { |s| search[/\A#{s}/] }
# => ["hello", "hell", "he", "he"]
答案 6 :(得分:0)
使用array#keep_if
array = ["hello", "hell", he"]
substrings = array.keep_if{|a| a.start_with?('h')}
=> ["hello", "hell", "he"]