如何在字符串中获得可能重叠的匹配 [英] How to get possibly overlapping matches in a string
本文介绍了如何在字符串中获得可能重叠的匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在寻找一种方法,无论是使用Ruby还是Javascript,它都会在字符串中针对正则表达式提供所有匹配,可能重叠。
I'm looking for a way, either in Ruby or Javascript, that will give me all matches, possibly overlapping, within a string against a regexp.
假设我有 str =abcadc
,我想找到 a $的出现次数c $ c>后跟任意数量的字符,后跟
c
。我要找的结果是 [abc,adc,abcadc]
。关于如何实现这一点的任何想法?
Let's say I have str = "abcadc"
, and I want to find occurrences of a
followed by any number of characters, followed by c
. The result I'm looking for is ["abc", "adc", "abcadc"]
. Any ideas on how I can accomplish this?
str.scan(/a.*c /)
将给出我 [abcadc]
, str.scan(/(?=(a。* c))/)。flatten
会给我 [abcadc,adc]
。
推荐答案
def matching_substrings(string, regex)
string.size.times.each_with_object([]) do |start_index, maching_substrings|
start_index.upto(string.size.pred) do |end_index|
substring = string[start_index..end_index]
maching_substrings.push(substring) if substring =~ /^#{regex}$/
end
end
end
matching_substrings('abcadc', /a.*c/) # => ["abc", "abcadc", "adc"]
matching_substrings('foobarfoo', /(\w+).*\1/)
# => ["foobarf",
# "foobarfo",
# "foobarfoo",
# "oo",
# "oobarfo",
# "oobarfoo",
# "obarfo",
# "obarfoo",
# "oo"]
matching_substrings('why is this downvoted?', /why.*/)
# => ["why",
# "why ",
# "why i",
# "why is",
# "why is ",
# "why is t",
# "why is th",
# "why is thi",
# "why is this",
# "why is this ",
# "why is this d",
# "why is this do",
# "why is this dow",
# "why is this down",
# "why is this downv",
# "why is this downvo",
# "why is this downvot",
# "why is this downvote",
# "why is this downvoted",
# "why is this downvoted?"]
这篇关于如何在字符串中获得可能重叠的匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文