-1

How do I create a regex to exactly match {{ variable } and ignore the {{ variable }}.

this what I have

text.match(/{{[^}]+}/g

but it's also matching {{ variable }} instead of just {{ variable }.

yivi
  • 42,438
  • 18
  • 116
  • 138
J. Doe
  • 11
  • 4

1 Answers1

-1

If you want to detect {{ variable } as valid and ignore {{ variable }}

You have to verify the end of the string using $

Regex Needed /{{[^}]+}$/g

Explanation

Visulization

enter image description here

const input1 = "{{ variable }";
console.log(input1.match(/{{[^}]+}$/g));

const input2 = "{{ variable }}";
console.log(input2.match(/{{[^}]+}$/g));

EDIT

If you want to detect { variable }} as valid and ignore {{ variable }}

You have to verify the start of the string with ^, also you have to check for negative lookahead for {{ using (?!{{)

Regex Needed /(?!{{)^{[^}]+}}$/g

Explanation

Visulization

enter image description here

const input1 = "{ variable }}";
console.log(input1.match(/(?!{{)^{[^}]+}}$/g));

const input2 = "{{ variable }}";
console.log(input2.match(/(?!{{)^{[^}]+}}$/g));
Nitheesh
  • 19,238
  • 3
  • 22
  • 49
  • 1
    thank you. this works! what about detecting `{ variable }}` ? trying to catch broken `{{ variable }}` format. – J. Doe Aug 30 '21 at 08:40
  • @J.Doe updated the answer – Nitheesh Aug 30 '21 at 10:06
  • so sorry for asking so much but im having a hard time wrapping my head around regex. the solution above matches `{ variable }}` but its not matching if there are characters before `{ variable }}` like `hey { variable }}` – J. Doe Aug 31 '21 at 08:56
  • the idea is to find `{ variable }}` in a block of text. thanks again – J. Doe Aug 31 '21 at 08:57