-2

I would like to write a regular expression which matches one or more occurrences of:

  • exactly two open curly braces, followed by
  • zero or more spaces, followed by
  • a dynamic string, followed by
  • zero or more spaces, followed by
  • exactly two closed curly braces

Let's say I have a fixed string hello. Then the regular expression which matches the above-mentioned pattern would be:

/({{\s*hello\s*}}){1,}/gi

In TypeScript, this would become:

const regExp: RegExp = /({{\s*hello\s*}}){1,}/gi;

If I were to use that regular expression with the following array of strings I would get these results:

  1. {{ hello }}: 1 match
  2. {{ hello}}: 1 match
  3. {{hello }}: 1 match
  4. {{hello}}: 1 match
  5. {hello}}: 0 matches
  6. {{hello}: 0 matches
  7. { hello }: 0 matches
  8. {{hello}}, how are you? {{ hello }}: 2 matches
  9. {{hello}}, how are you? {{ hello }} {{hello}}: 3 matches
  10. {{HELLO}}: 1 match

However, I am not able to achieve the same result by using a dynamic string.

Michael
  • 876
  • 9
  • 29
  • I really do not understand how the linked answer would answer my question. In [the accepted answer](https://stackoverflow.com/a/494046/3628251) they are using a static value, whereas my problem consisted in concatenating a piece of regular expression, the variable, and the other piece of regular expression. – Michael Aug 16 '21 at 09:41

1 Answers1

-1

I managed to find the solution by myself while writing the question. There are several different available approaches. The following regular expression initialisations are equivalent:

const key = 'hello';

// Static regular expressions
const regExp: RegExp = /({{\s*hello\s*}}){1,}/gi;
const staticSingleQuotedRegExp = new RegExp('({{\\s*hello\\s*}}){1,}', "gi");
const staticDoubleQuotedRegExp = new RegExp("(\{\{\\s*hello\\s*\}\}){1,}", "gi");

// Dynamic regular expressions
const dynamicSingleQuotedRegExp = new RegExp('({{\\s*' + key + '\\s*}}){1,}', "gi");
const backtickedRegExp = new RegExp(`({{\\s*${key}\\s*}}){1,}`, "gi");
const dynamicDoubleQuotedRegExp = new RegExp("(\{\{\\s*" + key + "\\s*\}\}){1,}", "gi");

Here is a stackblitz example.

Michael
  • 876
  • 9
  • 29
  • You forget that your approach will fail if `key` contains special regex metacharacters. See [this thread](https://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript). – Wiktor Stribiżew Aug 16 '21 at 08:05