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?"]
來源
2016-01-23 14:19:46
ndn
讀者:第一句話明確指出,所需要的是一個調用'all_matches(string,regex)'的方法,它可以處理任意字符串和正則表達式。 –
通常在使用正則表達式引擎時,匹配是「最長的」,除非你指定一個非貪婪的量詞,在那裏你得到「最左邊最短」的匹配。你無法真正期望在單一表達式中獲得最短和最長的時間。最短的時間,然後找到所有串聯排列將是最好的策略。 –
@theTinMan,原始問題指出,問題是關於給定正則表達式的匹配,這只是「讓我們說」一詞的一個例子。在你編輯之後,這個特定的正則表達式匹配看起來就像問題的要點。我不同意你的修改。 – ndn