javascriptregexl-systems

Can I use a regex capturing group to prevent successive matches of that group?


I have written a Javascript interpreter based on regular expressions. Is it possible to use capturing groups to prevent a successive match from evaluating any previously captured matches.

Example: I start with a string X. Here are two replacement rules:

X: 'F-[[X]+X]+F[+FX]-X'

F: 'FF'

pass 0: X is replaced by F-[[X]+X]+F[+FX]-X. Since F is not in the initial string it is ignored.

pass 1: here is where I want to use a capture group strategy. I first replace the 4 Xs. Now, how do I ignore those matches - presumably using capturing groups - and only evaluate the rest of the string?


Solution

  • Use a single regex with a replacer function instead, one that replaces xs with the desired x replacement, and fs with the desired f replacement, so they're all done at once, no need to mess with capturing groups:

    const replacements = {
      X: 'F-[[X]+X]+F[+FX]-X',
      F: 'FF'
    };
    const doReplace = str => str.replace(/[XF]/g, match => replacements[match]);
    const r1 = doReplace('X');
    const r2 = doReplace(r1);
    console.log(r1);
    console.log(r2);