0

I'm trying to replace tokens in a file. There can be multiple tokens on a line and the delimeters are &&.

Example:

{
  "host": "&&main_service&&/&&auth_endpoint&&"
}

If you use the regex:

const delimiter = '&&';
const delimeterRegex = new RegExp(`${delimiter}.*${delimiter}`);

...the problem is that that doesn't match individually; it can match that whole string (so I get ["&&main_service&&/&&auth_endpoint&&"] as a result, rather than getting ["&&main_service&&", "&&auth_endpoint&&"])

How do I get the two results separately, rather than together?

EDIT: Code I use to do the replace:

const findUnreplacedTokens = () => {
  console.log('Scanning for unreplaced tokens...');
  const errors = [];
  lines.forEach((ln, i) => {
    const tokens = delimeterRegex.exec(ln);
    if (tokens) {
      errors.push({
        tokens,
        line: i+1,
      });
    }
  });

  if (errors.length) {
    handleErrors(errors);
  } else {
    console.log('No rogue tokens found');
    console.log(logSpacing);
  }
};
user1775718
  • 1,499
  • 2
  • 19
  • 32

2 Answers2

0

With [^&] and g(global)

const delimeterRegex = new RegExp(`${delimiter}[^&]*${delimiter}`, 'g');

zelda11
  • 425
  • 2
  • 7
0

const regex = /&&(.*?)&&/g;
const str = `&&main_service&&/&&auth_endpoint&&`;
let m;

while ((m = regex.exec(str)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }
    
    // The result can be accessed through the `m`-variable.
    m.forEach(function(match, groupIndex) {
      if(match.indexOf("&&") !== -1) return;
        console.log(`Found match, group ${groupIndex}: ${match}`);
    });
}
Ryan
  • 295
  • 2
  • 8
  • This is correct. The problem I was having came in two parts: (1) The `?` to make it non-greedy (must go inside capture group); (2) MDN says that exec returns an array yet, that's not the whole story - exec acts more like an generator. You need to run the exec repeatedly to get matches. (https://stackoverflow.com/a/9214955/1775718 <-- helped too) – user1775718 Mar 01 '18 at 14:08