文本解析、条件文本
我有一个带有占位符的文本模板,我对其进行解析以替换占位符 具有真实的价值观。
文本模板:
Name:%name%
Age:%age%
我使用 StringBuilder.Replace() 来替换占位符
sb.Replace("%name%", Person.Name);
现在我想做更高级的算法。有些代码行是有条件的。他们 必须完全删除或保留。
文本模板
Name:%Name%
Age:%age%
Employer:%employer%
Employer 行仅应在人员受雇时出现(由布尔变量 Person.IsEmployed 控制)。
更新:我可以使用打开/关闭标签。如何找到字符串A和B之间的文本? 我可以使用正则表达式吗?如何?
I have a text template with placehoders that I parse in order to replace placeholders
with real values.
Text Template:
Name:%name%
Age:%age%
I use StringBuilder.Replace() to replace placeholders
sb.Replace("%name%", Person.Name);
Now I want to make more advanced algorithm. Some lines of code are conditional. They
have to be either removed completely of kept.
Text Template
Name:%Name%
Age:%age%
Employer:%employer%
The line Employer should appear only when person is employed (controlled by boolean variable Person.IsEmployed).
UPDATE: I could use open/close tags. How can find text between string A and B?
Can I use Regex? How?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
也许您可以在替换文本中包含标签“雇主:”而不是模板:
模板:
替换
Perhaps you could include the label "Employer:" in the replacement text instead of the template:
Template:
Replacement
另一种选择可能是使用模板引擎,例如 Spark 或 NVelocity。
请参阅 Spark 的快速示例< /a>
成熟的模板引擎应该让您能够最大程度地控制格式化输出。例如条件语句和重复部分。
Another alternative might be to use a template engine such as Spark or NVelocity.
See a quick example for Spark here
A full-fledged template engine should give you the most control over the formatted output. For example conditionals and repeating sections.
您当前的模板方案不够健壮 - 您应该添加更多特殊的占位符,例如:
您可以使用正则表达式解析 [if *] 块(未经测试):
但实际上,这个实现充满了漏洞。 ..您可能会更好地使用模板框架,就像另一个答案所建议的那样。
Your current templating scheme isn't robust enough - you should add more special placeholders, like this for example:
You can parse out [if *] blocks using a regex (not tested):
Really, though, this implementation is full of holes... You may be better off with a templating framework like another answer suggested.
一种选择是像现在一样进行所有替换,然后在出门时使用正则表达式替换来修复空变量。像这样的东西:
One option would be to do all of your replacement as you're doing now, then fix empty variables with a RegEx replacement on the way out the door. Something like this: