【发布时间】:2016-08-17 11:33:46
【问题描述】:
我需要用 Velocity 代码替换 HTML 文档中的一些自定义模板标签,以便输出可以在另一个应用程序中使用。
我收到的代码如下所示:
<BG SWITCH>param
<BG CASE>value1:
text 1
<BG /CASE>
<BG CASE>value2:
text 2
<BG /CASE>
<BG CASE>value3:
text 3
<BG /CASE>
<BG CASE>value4:
text 4
<BG /CASE>
<BG /SWITCH>
结果应该是这样的:
#set ($param = $!user.data.param)
#if($!param == "value1")
text 1
#end
#if($!param == "value2")
text 2
#end
#if($!param == "value3")
text 3
#end
#if($!param == "value4")
text 4
#end
我到现在为止的Java代码是这样的:
Pattern pattern = Pattern.compile("<BG SWITCH>(.+?)<BG CASE>(.+?):(.+?)<BG /CASE>", Pattern.DOTALL);
Matcher matcher = pattern.matcher(newHtml);
newHtml = matcher.replaceAll("#set \\(\\$$1\\ = \\$!user.data.$1) #if(\\$$1 == \"$2\")$3 #end");
我得到的结果是这样的:
#set ($param = $!user.data.param)
#if($param == "value1")
text 1
#end
<BG CASE>value2:
text 2
<BG /CASE>
<BG CASE>value3:
text 3
<BG /CASE>
<BG CASE>value4:
text 4
<BG /CASE>
<BG /SWITCH>
所以“开关”和第一个“案例”被正确替换,但我不知道如何替换以下案例。
有什么想法吗?
在 svasa 回答后编辑:
建议的解决方案非常适合我提供的示例代码,但我应该提到这只是来自要处理的实际文件的一个 sn-p。实际文件可能包含多个这样的 switch-case 块。在这种情况下,建议的代码并没有完全涵盖它。
当“源”看起来像这样时:
<div>
Some other content before
</div>
<div>
<BG SWITCH>param1
<BG CASE>value1:
text 1
<BG /CASE>
<BG CASE>value2:
text 2
<BG /CASE>
<BG CASE>value3:
text 3
<BG /CASE>
<BG CASE>value4:
text 4
<BG /CASE>
<BG /SWITCH>
</div>
<div>
Some other content between
</div>
<div>
<BG SWITCH>param2
<BG CASE>value1:
text 1
<BG /CASE>
<BG CASE>value2:
text 2
<BG /CASE>
<BG CASE>value3:
text 3
<BG /CASE>
<BG CASE>value4:
text 4
<BG /CASE>
<BG /SWITCH>
</div>
<div>
Some other content after
</div>
然后我得到以下结果:
#set ($param1 = $!user.data.param1)
#if($!param1== "value1")
text 1
#end
#if($!param1== "value2")
text 2
#end
#if($!param1== "value3")
text 3
#end
#if($!param1== "value4")
text 4
#end
#if($!param1== "value1")
text 1
#end
#if($!param1== "value2")
text 2
#end
#if($!param1== "value3")
text 3
#end
#if($!param1== "value4")
text 4
#end
因此,switch-case 块之前、之间和之后的任何其他内容都会丢失,第一个“param”用于第二个 switch-case 块。我将如何解决这个问题?
【问题讨论】:
标签: regex templates tags velocity