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 X
s. Now, how do I ignore those matches - presumably using capturing groups - and only evaluate the rest of the string?
Use a single regex with a replacer function instead, one that replaces x
s with the desired x
replacement, and f
s 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);