1

I found this difficult to explain (and search for) so let me try with an example.

The goal is a template system for a nodejs backend where I can replace custom tags in an HTML template with specific content based on certain params such as language.

A simple replace example:

<h1>{static||header}</h1>

My custom tag here can be replaced with:

template = template.replace(/{static\|\|(.*?)}/g, (match, $1) => { /* find the variable to replace $1 ("header") with and return */});

A more complex example where I loop through an array:

<ul>{static||items||loop||<li id="%k">%v</li>}</ul>

the code to replace it:

template = template.replace(/{static\|\|(.*?)}/g, (match, $1) => {
  // static parts
  let parts = $1.split("||");
  if(parts[1] === "loop"){
   /* loop through the "items" array replacing %k and %v as appropriate in parts[2] */
  }
});

But now I have run into a new challenge I need to solve and my regex ability is somewhat lacking to solve this so I am turning to StackOverflow for ideas.

The problem I need to solve is a loop, as above, but within that loop are more tags, these could be simple replacements or looped replacements. The point is, the regex needs to find the closing } for the outer tag and ignore any tags and variables that are within it.

Html example:

<ul>{static||items||loop||<li id="%k"> <strong>{static||foo}: %v</strong> <ul>{static||subitems||loop||<li>%v</li>}</ul> </li>}</ul>

So the regex should match the first "{static" to the last "}" and ignore the 2 "{static...}" that are within it. How can the regex "know" that the correct closing "}" is the last one?

Many thanks!

  • S.O. generally doesn't like people using regex on HTML. https://meta.stackoverflow.com/questions/252390/the-famous-tag-regex-answer-should-its-title-be-edited – QuentinUK Apr 12 '20 at 02:25
  • https://stackoverflow.com/questions/546433/regular-expression-to-match-balanced-parentheses – Adelin Apr 12 '20 at 02:34
  • the html here is irrelevant. the template could be any kind of content. – Thomas Smart Apr 12 '20 at 03:27
  • the 546433 post is interesting @Adelin, recursion/nesting seems to be a challenge in javascript regex, but will see what I can do with the example provided there. – Thomas Smart Apr 12 '20 at 03:31
  • I don't think this is a particularly good use case for regex. When your examples keep adding complexity to the point where you're needing recursion and bracket matching, it's probably time to switch to a parser. It's not so much your regex ability as it is the tool itself, which simply is poorly equipped to handle counting and nesting. – ggorlen Apr 12 '20 at 03:48

0 Answers0