Reputation: 23
I have the following situation. I have a pattern like this:
Hi, my name is ${name}, I am ${age} years old. I live in ${address}
I want to get the value of those tokens within any sentence:
Hi, my name is Peter, I am 22 years old. I live in San Francisco, California
So, I need the key=value in a Dictionary<string, string>
:
${name} = "Peter",
${age} = "22",
${address} = "San Francisco, California"
Upvotes: 2
Views: 1724
Reputation: 10427
Convert your patter to a regex with named capturing groups:
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]);
}
Upvotes: 2
Reputation: 1384
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]);
}
Upvotes: 1
Reputation: 741
Have you tried using Regex? This is a classic Regular Expression. One that fits your sentence :
Hi, my name is (?<name>.*), I am (?<age>.*) years old\. I live in (?<address>.*)
Usage example :
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>.*)");
Now, to access the specific groups :
match.Groups["name"], match.Groups["age"], match.Groups["address"]
These will give you your values. Of course, you should first check match.IsSuccess
to see if the Regex was matched.
Upvotes: 4
Reputation: 6982
One easy way of doing it by using String.Format
method. For Example:
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.
For more reference on String.Formate
, see:
http://msdn.microsoft.com/en-us/library/system.string.format.aspx
Upvotes: 1