Regex for inner tag detection

  Kiến thức lập trình

I have a document generation application that handles tag replacement, I use a regular expression to detect said tags. These tags can be of multiple types, for the sake of the problem let’s take into account the following:

  • {{text to replace::S}} – Simple tag, in-line text replacement
  • {{content to include::C}} – Choice tag, allows the user to include, or not, the tag content.
  • {{option 1 / option 2::A}} – Alternative tag, allows the user to choose between option 1 or option 2

I’ve worked with these without a problem and detected them using this RegeX expression /{{([^:]+)::([S|C|R|A])}}/g

I want to introduce nested tags, and that’s where the problem is. I’ve tried multiple approaches.

First approach Try it here

/{{([^{]+(?:{{[^{}]*}})?)::([S|C|R|A])}}/g this allows me to detect only one nested tag but, as you can see the Alternative tag has problems with it.

Second approach Try it here

/{{(.+(?:{{[^{}]*}})?)::([S|C|R|A])}}/g this detects multiple nested tags but, when a text has multiple tags it breaks.

Any help?

Theme wordpress giá rẻ Theme wordpress giá rẻ Thiết kế website

LEAVE A COMMENT