我想在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有一种更简单的方法。
答案 0 :(得分:2)
var res = Regex.Matches(targetString, @"%%(.+?)%%").Cast<Match>()
.Select(m => m.Groups[1].Value)
.ToList();
答案 1 :(得分:1)
您可以尝试类似%%([^(%%)].*?)%%
的内容,并在索引1处获取匹配的组。
程序中使用的字符串文字:
@"%%([^(%%)].*?)%%"
正则表达式代表%%
后跟任何内容,直到找到%%
。
此处括号()
用于分组。我测试了它here
答案 2 :(得分:1)
听起来你正试图建立某种模板系统。您可能希望查看可用的模板引擎,例如StringTemplate
。
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.
尼斯!