1

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?

dugla
  • 12,774
  • 26
  • 88
  • 136
  • 1
    So, for example, you want a string of `XF` to turn into `F-[[X]+X]+F[+FX]-XFF` rather than `FF-[[X]+X]+FF[+FFX]-XFF`, is that it? – CertainPerformance Oct 02 '18 at 00:57
  • Show some intermediate steps. Like pass 1 in more detail. Normally to _ignore_ something, you have to _match_ it, then write it back. `((?:F-\[\[X\]+X\]+F\[+FX\]-X)*)|((?:(?!F-\[\[X\]+X\]+F\[+FX\]-X).)+)` –  Oct 02 '18 at 01:05
  • Indeed @CertainPerformance. I currently use a hack of adding a junk guard symbol that I discard after all matches are run. Your answer is just the ticket dude. – dugla Oct 02 '18 at 13:03

1 Answers1

1

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);
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320