Home > Mobile >  Javascript RegEx Templating Edge Case
Javascript RegEx Templating Edge Case

Time:01-18

I have a RegEx implemented with JavaScript that is close to doing what I want. However, I am having an issue figuring out the last piece which is causing an issue with an edge case. Here is the RegEx that I have so far:

/\$\{(. ?(}\(. ?\)|}))/g

The idea is that this RegEx would use a templating system to replace/inject variables in a string based on templated variables. Here is an example of the edge case issue:

"Here is a template string ${G:SomeVar:G${G:SomeVar:G} that value gets injected in."

The problem is the RegEx is matching this:

"${G:SomeVar:G${G:SomeVar:G}"

What I want it to match is this:

"${G:SomeVar:G}"

How would I get the RegEx to match the expected variable in this edge case?

CodePudding user response:

Instead of matching anything with (. ?), change it to not match another closing brace or dollar sign, [^{$].

\$\{([^{$] ?(}\(. ?\)|}))
  • Related