Home > Back-end >  regex Supplant js
regex Supplant js

Time:04-18

Sorry i can't speak english :(

I write Supplant I have a regex

({{([']).*\2}})

needs regex to detect what is in a rectangle

enter image description here

I need it rigidly between {{' - '}} because there can be any character between the quotation marks (e.g. one { )

best to use it \1 because regex is more longer

Thanks for the help. Regards

CodePudding user response:

This can work for you:

/\{\{'((?:(?!\{\{').)*?)'\}\}/g
  • \{\{' - start by matching {{'.
  • ( ... ) - if you're writing a template engine you probably care about what's inside the curly braces and quotes. This captures the string inside the quotes so you'll be able to use it.
  • (?: ... ) - a non-captureing group (the value here will not be used).
  • (?!\{\{'). - match anything, except if we're seeing another {{'.
  • (?!\{\{').)*? - *? is a lazy match, so we'll stop at the first '}}
  • and finally, the closing '}}

as code it will looks something like this - I included a function to set the replaced value, because typically that's what you'd do in a template engine:

let s = "n {{'a{123456789}'}} n {{\"a{123456789}\"}} n {{'a{1234{{'a{12345{{'a{123456789}'}}6789}'}}56789}'}} ";
s = s.replace(/\{\{'((?:(?!\{\{').)*?)'\}\}/g, (wholeMatch, capturedKey) => {
  console.log('captured key:', capturedKey);
  return "REPLACED "   capturedKey;
});
console.log(s);

if you want to support double quotes it becomes a bit more complicated:

s = s.replace(/\{\{(["'])((?:(?!\{\{["']).)*?)\1\}\}/g, 
              (wholeMatch, quote, capturedKey) => { ... }
);

CodePudding user response:

Try this:/{{'(?!. ?{{)([^'] )/gm

This basically looks for the {{' which doent have any other {{ in front of it then, matches everything till the first '.

Test here: https://regex101.com/r/rw6kkP/1

var myString = `{{'a{everysign}a'}}
{{'a{every{{'a{everysign}a'}}sign}a'}}
{{'a{every{{'a{every{{'a{inside content}a'}}sign}a'}}sign}a'}} `;

var myRegexp = /{{'(?!. ?{{)([^'] )/gm;

match = myRegexp.exec(myString);
while (match != null) {
  // match[0] returns the whole match: {{'a{everysign}a
  // match[1] returns the capture group which is the required content: a{everysign}a
  console.log(match[1])
  match = myRegexp.exec(myString);
}

  • Related