我想在C#中用字符串创建一些通配符。这样,终端用户就可以用通配符填充一大团文字。想象一下:
var targetString = 
@"There is a banana in this %%object%%.   
For this, we use %%type of tool%% to remove it.";假设%%是通配符分隔符。代码将解析第一个%%和后面%%,并确定通配符为object和type of tool。将它们作为字符串数组返回将非常困难,只要我能够遍历文本中的所有伪通配符,这并不重要。
有人能给我提供一些正则表达式(或C#字符串操作)的线索吗?我当然可以打破我以前的VBScript方法,开始基于%%拆分这个字符串--但是这是非常低效率的,而且我怀疑在C#字符串上使用Regex有一种更简单的方法。
发布于 2014-06-25 19:50:55
听起来你在尝试建立某种模板系统。与其滚动您自己的引擎,您可能希望查看现成的模板引擎,如StringTemplate。
ST允许您这样做:
using Antlr4.StringTemplate;
Person person = new Person() ;
person.Name = "John" ;
person.Street = "123 Main St" ;
person.City   = "Anytown" ;
person.Zip    = 12345 ;
Template hello = new Template("Hello. My name is <p.Name>. My Address is <p.Street>, <p.City>,  <p.State> <p.Zip>.");
hello.Add("p", person);
Console.Out.WriteLine(hello.Render());并将预期的文本写入控制台:
Hello. My Name is John. My address is 123 Main St, Anytown, PA 12345.好的!
https://stackoverflow.com/questions/24416151
复制相似问题