在字符串c#中查找标记值

时间:2013-06-05 07:22:30

标签: c# string token

我有以下情况。我有这样的模式:

  

嗨,我的名字是$ {name},我是$ {age}岁。我住在$ {address}

我希望在任何句子中获得这些令牌的价值:

  

嗨,我的名字是彼得,我今年22岁。我住在加利福尼亚州的旧金山

所以,我需要Dictionary<string, string>中的key =值:

${name} = "Peter",
${age} = "22",
${address} = "San Francisco, California"

4 个答案:

答案 0 :(得分:4)

您是否尝试过使用Regex? 这是一个经典的正则表达式。 一个适合你的句子:

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以查看正则表达式是否匹配。

答案 1 :(得分:2)

将您的模式转换为具有命名捕获组的正则表达式:

    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]);
    }

答案 2 :(得分:1)

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]);
            }

答案 3 :(得分:1)

使用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