How to get possibly overlapping matches in a string

后端 未结 8 2144
别那么骄傲
别那么骄傲 2020-12-03 17:13

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.


Let\'s say I have

8条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-03 17:55

    ▶ str = "abcadc"
    ▶ from = str.split(/(?=\p{L})/).map.with_index { |c, i| i if c == 'a' }.compact
    ▶ to   = str.split(/(?=\p{L})/).map.with_index { |c, i| i if c == 'c' }.compact
    ▶ from.product(to).select { |f,t| f < t }.map { |f,t| str[f..t] }
    #⇒ [
    #  [0] "abc",
    #  [1] "abcadc",
    #  [2] "adc"
    # ]
    

    I believe, that there is a fancy way to find all indices of a character in a string, but I was unable to find it :( Any ideas?

    Splitting on “unicode char boundary” makes it to work with strings like 'ábĉ' or 'Üve Østergaard'.

    For more generic solution, that accepts any “from” and “to” sequences, one should introduce just a little modification: find all indices of “from” and “to” in the string.

提交回复
热议问题