搜索字符串返回多个可变长度Ruby正则表达式的所有重叠事件的索引

时间:2016-10-19 00:53:26

标签: ruby regex tuples irb

我在Interactive Ruby(IRB)$ irb中使用以下代码来搜索字符串(即evidence)并返回元组数组(guilty_term_indexes)。每个元组的第二个元素表示evidence字符串中的字符索引,其中找到guilty_term的第一个字符(存储在元组的第一个元素中)。

guilty_terms = [/danger/i, /hack/i, /ckdd/i]
regex_guilty_terms = Regexp.union(guilty_terms)
evidence = "hackddangerhackdanger"
guilty_terms_and_indexes = []
evidence.scan(regex_guilty_terms) do |index|
    guilty_term = Regexp.last_match.offset(0)[0]
    guilty_terms_and_indexes << [index, guilty_term]
end
p guilty_terms_and_indexes

期待 guilty_terms_and_indexes返回: [["hack", 0], ["ckdd", 2], ["danger", 5], ["hack", 11], ["ckdd", 13], ["danger", 15]] 但它返回: [["hack", 0], ["danger", 5], ["hack", 11], ["danger", 15]]

如何获得预期的结果?

系统

$ ruby -v ruby 2.3.1p112 (2016-04-26 revision 54768) [x86_64-darwin15]

2 个答案:

答案 0 :(得分:2)

匹配不能重叠。改为使用零长度断言:

guilty_terms = [/danger/i, /hack/i, /ckdd/i]

# the positive lookahead is where the magic happens
regex_guilty_terms = /(?=(#{Regexp.union(guilty_terms)}))/
evidence = "hackddangerhackdanger"

# just a squeezin'
[].tap { |arr| evidence.scan(regex_guilty_terms) { |x| arr << [$1, $~.begin(1)] } }
# => [["hack", 0], ["ckdd", 2], ["danger", 5], ["hack", 11], ["danger", 15]]

位置13没有打印,因为它实际上并不匹配,所以...不确定如何获得预期结果:)

答案 1 :(得分:1)

您不必使用正则表达式。

terms = %w| Danger hack ckdd |
  #=> ["Danger", "hack", "ckdd"]
evidence = "Hackddangerhackddanger"

down_terms = terms.map(&:downcase)
  #=> ["danger", "hack", "ckdd"] 
down_evidence = evidence.downcase
  #=> "hackddangerhackddanger" 

down_evidence.size.times.with_object([]) do |i,a|
  w = down_terms.find { |w| down_evidence[i..-1].start_with?(w) }
  a << [w,i] unless w.nil?
end
  # => [["hack",0], ["ckdd",2], ["danger",5], ["hack",11], ["ckdd",13], ["danger",16]]