作者:追求生活的垃圾筒 | 来源:互联网 | 2023-09-16 12:25
Iamworkingonasimpletokenreplacementfeatureofourproduct.Ihavealmostresolvedalltheis
I am working on a simple token replacement feature of our product. I have almost resolved all the issue but I missed one thing. A token must support attributes, and an attribute can also be a token. This is part of a bigger project. hope you can help.
我正在研究我们产品的简单令牌替换功能。我几乎解决了所有问题,但我错过了一件事。令牌必须支持属性,属性也可以是令牌。这是一个更大项目的一部分。希望你能帮忙。
The begining tag is "**#[**"
and the ending tag is "**]**"
. Say, #[FirstName], #[LastName], #[Age, WhenZero="Undisclosed"].
开头的标签是“**#[**”,结尾标签是“**] **”。比如,#[FirstName],#[LastName],#[Age,WhenZero =“Undisclosed”]。
Right now i am using this expression "\#\[[^\]]+\]"
. I have this working but it failed on this input:
现在我正在使用这个表达式“\#\ [[^ \]] + \]”。我有这个工作,但它输入失败:
blah blah text here...
**#[IsFreeShipping, WhenTrue="
$[FreeShipping]"]**
blah blah text here also...
It fails becauise it encouter the first ], it stops there. It returns:
它失败了因为它包围了第一个],它停在那里。它返回:
*#[IsFreeShipping, WhenTrue="
$[Product_FreeShipping]*
My desired result should be
我想要的结果应该是
*#[IsFreeShipping, WhenTrue="
$[FreeShipping]"]*
7 个解决方案
This is a little border-line for a regexp, since it depends on a context, but still...
这是正则表达式的一个小边界线,因为它取决于上下文,但仍然......
#\[(\](?=")|[^\]])+\]
should do it.
应该这样做。
The idea is to mention a closing square bracket can be part of the parsed content if followed by a double quotes, as part of the end of an attribute.
这个想法是提到一个结束方括号可以是解析内容的一部分,如果后跟双引号,作为属性结尾的一部分。
If that same square bracket were anywhere within the attribute, that would be a lot harder...
如果同一个方括号在属性中的任何位置,那将会更加困难......
The advantage with lookahead expression is that you can specify a regexp with a non-fixed match length.
So if the attribute closing square bracket is not followed by a double quote, but rather by another known expression, you just update the lookahead part:
前瞻表达式的优点是您可以指定具有非固定匹配长度的正则表达式。因此,如果关闭方括号的属性后面没有双引号,而是另一个已知表达式,则只需更新前瞻部分:
#\[(\](?=")|[^\]])+\]
will match only the second closing square bracket, since the first is followed by "
.
将仅匹配第二个结束方括号,因为第一个后跟“。
Of course, any kind of greedy expression (.*]
) would not work, since it would not match the second closing square bracket, but the last one. (Meaning if there are more the one intermediate ]
, it will be parsed.)
当然,任何一种贪婪的表达式(。*]都不会起作用,因为它与第二个结束方括号不匹配,而是最后一个。 (意思是如果有更多的中间],它将被解析。)