我有以下情况。我有这样的模式:
嗨,我叫 ${name},今年 ${age} 岁。我住在 ${address}
我想在任何句子中获得这些标记的价值:
你好,我的名字是彼得,我今年 22 岁。我住在加利福尼亚州旧金山
所以,我需要 a 中的 key=value Dictionary<string, string>
:
${name} = "Peter",
${age} = "22",
${address} = "San Francisco, California"
您是否尝试过使用正则表达式?这是一个经典的正则表达式。一个适合你的句子:
Hi, my name is (?<name>.*), I am (?<age>.*) years old\. I live in (?<address>.*)
用法示例:
Match match = Regex.Match(@"Hi, my name is Peter, I am 22 years old. I live in San Fransisco, California", @"Hi, my name is (?<name>.*), I am (?<age>.*) years old\. I live in (?<address>.*)");
现在,要访问特定组:
match.Groups["name"], match.Groups["age"], match.Groups["address"]
这些会给你你的价值观。当然,您应该首先检查match.IsSuccess
Regex 是否匹配。
将您的模式转换为具有命名捕获组的正则表达式:
string pattern = "Hi, my name is ${name}, I am ${age} years old. I live in ${address}";
string input = "Hi, my name is Peter, I am 22 years old. I live in San Francisco, California";
string resultRegex = Regex.Replace(Regex.Escape(pattern), @"\\\$\\\{(.+?)}", "(?<$1>.+)");
Regex regex = new Regex(resultRegex);
GroupCollection groups = regex.Match(input).Groups;
Dictionary<string, string> dic = regex.GetGroupNames()
.Skip(1)
.ToDictionary(k => "${"+k+"}",
k => groups[k].Value);
foreach (string groupName in dic.Keys)
{
Console.WriteLine(groupName + " = " + dic[groupName]);
}
string Template = "Hi, my name is ${name}, I am ${age} years old. I live in ${address}";
Dictionary<string, string> KeyValuePair=new Dictionary<string,string>();
KeyValuePair.Add("${name}", "Peter");
KeyValuePair.Add("${age}", "22");
KeyValuePair.Add("${address}", "San Francisco, California");
foreach (var key in KeyValuePair.Keys)
{
Template = Template.Replace(key, KeyValuePair[key]);
}
使用方法的一种简单String.Format
方法。例如:
string pattern="Hi, my name is {0}, I am {1} years old. I live in {2}";
string result= String.Format(patter,name,age,address);//here name , age, address are value to be placed in the pattern.
有关 的更多参考String.Formate
,请参阅:
http://msdn.microsoft.com/en-us/library/system.string.format.aspx