文本解析,条件文本。

4
我有一个文本模板,其中包含占位符,我解析它以替换占位符为实际值。
文本模板:
Name:%name%
Age:%age%

我使用 StringBuilder.Replace() 方法来替换占位符。
sb.Replace("%name%", Person.Name);

现在我想要编写更高级的算法。有些代码行是有条件的,它们必须要么完全删除,要么保留下来。
文本模板
Name:%Name%
Age:%age%
Employer:%employer%

“当人的就业状态由布尔变量Person.IsEmployed控制时,雇主一词应该只出现一次。”
“更新:我可以使用开放/关闭标签。如何找到A和B之间的文本?我可以使用正则表达式吗?怎么用?”
4个回答

4
也许你可以在替换文本中包含“雇主:”标签,而不是模板:

模板:

Name:%Name%
Age:%age%
%employer%

替换

sb.Replace("%employer%", 
    string.IsNullOrEmpty(Person.Employer) ? "" : "Employer: " + Person.Employer)

如何将标签设置为仅与特定文本区域相关联? 我认为我需要引入开放/关闭标签。 - Captain Comic

2
另一个选择可能是使用模板引擎,例如SparkNVelocity

这里查看快速示例

完整的模板引擎应该能够为您提供对格式化输出的最大控制。例如条件和重复部分。


1

一个选择是像您现在这样进行所有替换,然后在出门时使用正则表达式替换来修复空变量。像这样:

Response.Write(RegEx.Replace(sb.ToString(), "\r\n[^:]+:r\n", "\r\n"));

1

你当前的模板方案不够健壮 - 你应该添加更多的特殊占位符,比如这个:

Name:%Name%
Age:%age%
[if IsEmployed]
Employer:%employer%
[/if]

你可以使用正则表达式(未经测试)来解析 [if *] 块:

Match[] ifblocks = Regex.Match(input, "\\[if ([a-zA-Z0-9]+)\\]([^\\[]*)\\[/if\\]");
foreach(Match m in ifblocks) {
    string originalBlockText = m.Groups[0];
    string propertyToCheck = m.Groups[1];
    string templateString = m.Groups[2];

    // check the property that corresponds to the keyword, i.e. "IsEmployed"

    // if it's true, do the normal replacement on the templateString
    // and then replace the originalBlockText with the "filled" templateString

    // else, just don't write anything out
}

实际上,这个实现存在很多漏洞...你可能最好使用像另一个答案建议的模板框架。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接