简体   繁体   English

Javascript regexp模板:仅在括号内的字符串相等时匹配

[英]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. 我正在为我正在建设的网站使用javascript模板系统,我遇到了一些问题。

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. 在声明“user”= true时,显示字符串。 When "is_user" is set to false, the string is not shown. 当“is_user”设置为false时,不显示该字符串。 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? 因此意味着匹配在{{#is_user?}}和{{/ has_picture?}}之间找到,因为正则表达式只检查{{#anystring?}}和{{/ 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?}}. 现在我的问题是,如果括号之间的两个字符串相等,可以说只有一个匹配,那么匹配只能在{{#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 (.*?). \\ 3(或\\ 1)将包含第一个(。*?)的值。

See it on rubular . 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. 也许这足以满足您的具体情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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