简体   繁体   中英

Javascript regexp templates: only match when string inside brackets is equal

I'm working with a javascript templating system for a website I'm building and I'm having a bit a of problem.

I'm using the following regex to match with sections within my string:

 /(\{\{(#|\^)(.*?)\?\}\}(.*?)\{\{\/(.*?)\?\}\})/

Feeding this a string such as:

 {{#is_user?}} The user is an user {{/user?}}

While stating "user"=true, displays the string. When "is_user" is set to false, the string is not shown. However I've found that this allows no room for nesting as such that:

 {{#is_user?}} The user is an user {{#has_picture?}} and has a picture{{/has_picture?}} {{/user?}}

This will result in the following:

The user is an user  {#is_user?}} The user is an user{{/user?}}   

Thus meaning the the match is found between {{#is_user?}} and {{/has_picture?}} as the regex just checks for a match between {{# anystring ?}} and {{/ anystring? }}.

Now my question is if its possible to say that there's only a match if the two strings between the brackets are equal so that a match is only found when {{#stirngA?}} {{/stringA?}}.

You can make your regex only match the corresponding opening tag by using backreferences.

Eg:

/(\{\{(#|\^)(.*?)\?\}\}(.*?)\{\{\/(\3)\?\}\})/

or without capturing all groups:

/(?:\{\{(?:#|\^)(.*?)\?\}\}(.*)\{\{\/(?:\1)\?\}\})/

The \\3 (or \\1) will contain the value of the first (.*?).

See it on rubular .

But this might not fully solve your problem of nested matches. Although you could use the result and apply the regex again. Maybe thats enough for your specific case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM