如何在字符串中获取可能重叠的匹配项

编程入门 行业动态 更新时间:2024-10-28 18:25:58
本文介绍了如何在字符串中获取可能重叠的匹配项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在寻找一种方法,无论是在 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?"]

更多推荐

如何在字符串中获取可能重叠的匹配项

本文发布于:2023-11-01 17:26:34,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1549945.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   如何在

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!