Javascript正则表达式模板:仅当括号内的字符串相等时才匹配

发布于 2025-01-01 14:16:36 字数 758 浏览 2 评论 0原文

我正在为我正在构建的网站使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

温馨耳语 2025-01-08 14:16:36

您可以使用反向引用使正则表达式仅匹配相应的开始标记。

例如:

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

或者不捕获所有组:

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

\3(或\1)将包含第一个(.*?)的值。

请在 rubular 上查看。

但这可能无法完全解决您的嵌套匹配问题。尽管您可以使用结果并再次应用正则表达式。也许这对于您的具体情况来说就足够了。

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

E.g.:

/(\{\{(#|\^)(.*?)\?\}\}(.*?)\{\{\/(\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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文