Javascript正则表达式模板:仅当括号内的字符串相等时才匹配
我正在为我正在构建的网站使用 javascript 模板系统,但遇到了一些问题。
我使用以下正则表达式来匹配字符串中的部分:
/(\{\{(#|\^)(.*?)\?\}\}(.*?)\{\{\/(.*?)\?\}\})/
向其提供一个字符串,例如:
{{#is_user?}} The user is an user {{/user?}}
在声明“user”= true 时,显示该字符串。当“is_user”设置为 false 时,不显示该字符串。但是我发现这不允许嵌套空间:
{{#is_user?}} The user is an user {{#has_picture?}} and has a picture{{/has_picture?}} {{/user?}}
这将导致以下结果:
The user is an user {#is_user?}} The user is an user{{/user?}}
因此意味着在 {{#is_user?}} 和 {{/has_picture?}} 之间找到匹配,因为正则表达式只是检查 {{#anystring ?}} 和 {{/anystring?} 之间是否匹配}}。
现在我的问题是,如果括号之间的两个字符串相等,是否可以说只有一个匹配,这样只有在 {{#stirngA?}} {{/stringA?}} 时才能找到匹配。
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?}}.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用反向引用使正则表达式仅匹配相应的开始标记。
例如:
或者不捕获所有组:
\3(或\1)将包含第一个(.*?)的值。
请在 rubular 上查看。
但这可能无法完全解决您的嵌套匹配问题。尽管您可以使用结果并再次应用正则表达式。也许这对于您的具体情况来说就足够了。
You can make your regex only match the corresponding opening tag by using backreferences.
E.g.:
or without capturing all groups:
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.