问题描述
我正在寻找一种方法,无论是在 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代码>.我正在寻找的结果是
["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"]
.
str.scan(/a.*c/)
will give me ["abcadc"]
, str.scan(/(?=(a.*c))/).flatten
will give me ["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?"]
这篇关于如何在字符串中获取可能重叠的匹配项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!