字符串包括数组中的子字符串

时间:2019-02-27 18:24:36

标签: ruby

我有以下内容:

input string = "1234"
output new_array should = [12, 3, 4, 34]

2 个答案:

答案 0 :(得分:2)

def string_to_array(string)
  noun = ["d", "fgh", "i", "jk", "bcd", "cdef"]
  verb = ["cd", "ef", "f", "jkl", "abc"]

  ary = (noun+verb).select { |s| string.include? s }
  ary.unshift(ary.delete(string)).compact
end

string = "cdef"

string_to_array(string) #=> ["cdef", "d", "cd", "ef", "f"]

我使用了Array#selectArray#+Array#deleteArray#unshiftArray#compactString#include?

如果要从输出数组中删除重复项,请使用Array#uniq

答案 1 :(得分:0)

您可以将String#scan(尤其是文档的最后一句话)与正则表达式一起使用。我的目的是演示这种方法,而不是建议它是首选方法。

nouns = ["cdef", "d", "fgh", "i", "jk", "bcd"]
verbs = ["cd", "ef", "f", "jkl", "abc"]

R = Regexp.new (nouns+verbs).map { |s| "(?=(#{s}))?" }.join
  #=> /(?=(cdef))?(?=(d))?(?=(fgh))?(?=(i))?(?=(jk))?(?=(bcd))?(?=(cd))?(?=(ef))?(?=(f))?(?=(jkl))?(?=(abc))?/ 

def string_to_array(str, nouns, strings)
  str.scan(R).flatten.compact
end

str = "cdef"

string_to_array(str, nouns, verbs)
  #=> ["cdef", "cd", "d", "ef", "f"]

注意:

str.scan(R)
  #=> [["cdef", nil, nil, nil, nil, nil, "cd", nil, nil, nil, nil],
  #    [nil, "d", nil, nil, nil, nil, nil, nil, nil, nil, nil],
  #    [nil, nil, nil, nil, nil, nil, nil, "ef", nil, nil, nil],
  #    [nil, nil, nil, nil, nil, nil, nil, nil, "f", nil, nil],
  #    [nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil]] 

(?=(cdef))?(?=(cdef)?)也有效)是捕获组中的正向超前。它要求字符串中的特定位置后跟先行内容,但不属于匹配项本身。问号使前瞻性成为可选。