Home > Back-end >  Regex Expression to match balanced double curly braces stored in an XML document
Regex Expression to match balanced double curly braces stored in an XML document

Time:10-08

I have a bit of an odd use case. I need to determine if a given string contains a "variable" within double curly braces; such as {{date}}. The below table represents the some of the use cases and the regex I am using, (?<!\{)\{\{(?:([^{}] ))}}(?!}), gives me the desired results.

string/variable result
text {{date}} text true
text {date}} text false
text {{date} text false
text {date{date}} text false
text {{date}date} text false
text {{{date}}} text true
text {date{{date}}date} text true
text {{date}} some text {date}} text true

However, the problem I have is that I am required to have all JavaScript functions stored within an XML document.

Sort of like this:

<script_node>
   function foo(TextWithEmbeddedVars){
     var check = /(?<!\{)\{\{(?:([^{}] ))}}(?!})/.test(TextWithEmbeddedVars);
     return check;
   } 
</script_node>

Because the function is in an XML node the less than ("<") and greater than (">") symbols have to be written as &lt; or &gt; in order to not break the XML doc. But when you do this, (?&lt;!\{)\{\{(?:([^{}] ))}}(?!}), it breaks the regex pattern and it ceases to work.

Is there either a way to rewrite the regex to not require the less than symbol or a different way to write it and make it XML friendly?

Thanks, Jeff

CodePudding user response:

Enclosing the function string in a CDATA section should solve the problem as there's no need to escape reserved XML characters inside a CDATA section. It is the recommended way of doing this.

<script_node><![CDATA[
   function foo(TextWithEmbeddedVars){
     var check = /(?<!\{)\{\{(?:([^{}] ))}}(?!})/.test(TextWithEmbeddedVars);
     return check;
   }]]>
</script_node>
  • Related