Home > Software design >  Regex, how to detect value in double curly braces?
Regex, how to detect value in double curly braces?

Time:04-19

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 doesn't have any other {{ in front of it then, matches everything till the first '.

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

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

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

console.log(myString.match(myRegexp))
// [ "a{content 1}a", "a{everysign}a", "a{inside content}a" ]

  • Related