How to get all possible overlapping matches for a string

后端 未结 2 1757
醉梦人生
醉梦人生 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-03 23:58

    Here's the regex you need: /III/g - simple enough, right? Now here's how you use it:

    var text = "MUIIIUIIIU", find = "III", replace "U",
        regex = new RegExp(find,"g"), matches = [], match;
    while(match = regex.exec(text)) {
        matches.push(match);
        regex.lastIndex = match.index+1;
    }
    

    That regex.lastIndex... line overrides the usual regex behaviour of not matching results that overap. Also I'm using a RegExp constructor to make this more flexible. You could even build it into a function this way.

    Now you have an array of match objects, you can do this:

    matches.forEach(function(m) { // older browsers need a shim or old-fashioned for loop
        console.log(text.substr(0,m.index)+replace+text.substr(m.index+find.length));
    });
    

    EDIT: Here is a JSFiddle demonstrating the above code.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题