我在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]
答案 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]]