How to get all possible overlapping matches for a string

后端 未结 2 1772
醉梦人生
醉梦人生 2020-12-03 23:12

I\'m working on the MIU system problem from \"Gödel, Escher, Bach\" chapter 2.

One of the rules states

Rule III: If III occurs in one of the strings in

2条回答
  •  天涯浪人
    2020-12-04 00:01

    Sometimes regexes are overkill. In your case a simple indexOf might be fine too!

    Here is, admittedly, a hack, but you can transform it into pretty, reusable code on your own:

    var s = "MIIIIIUIUIIIUUIIUIIIIIU";
    var results = [];
    for (var i = 0; true; i += 1) {
        i = s.indexOf("III", i);
        if (i === -1) {
            break;
        }
        results.push(i);
    }
    console.log("Match positions: " + JSON.stringify(results));
    

    It takes care of overlaps just fine, and at least to me, the indexOf just looks simpler.

提交回复
热议问题