5

在我的程序中,您可以编写一个可以编写变量的字符串。

例如:

我的狗的名字是 %x%,他有 %y% 岁。

我可以替换的词是介于%%. 所以我需要一个函数来告诉我在那个字符串中有哪些变量。

GetVariablesNames(string) => result { %x%, %y% }
4

2 回答 2

7

我会使用正则表达式来查找任何看起来像变量的东西。

如果您的变量是百分号、任意字字符、百分号,那么以下应该有效:

string input = "The name of my dog is %x% and he has %y% years old.";

// The Regex pattern: \w means "any word character", eq. to [A-Za-z0-9_]
// We use parenthesis to identify a "group" in the pattern.

string pattern = "%(\w)%";     // One-character variables
//string pattern ="%(\w+)%";  // one-or-more-character variables

// returns an IEnumerable
var matches = Regex.Matches(input, pattern);

foreach (Match m in matches) { 
     Console.WriteLine("'{0}' found at index {1}.", m.Value, m.Index);
     var variableName = m.Groups[1].Value;
}

MSDN:

于 2012-12-09T15:31:17.247 回答
1

您可以使用正则表达式来获取出现次数,并将它们分组以计算每个事件的出现次数。例子:

string text = "The name of my dog is %x% and he has %y% years old.";

Dictionary<string, int> keys =
  Regex.Matches(text, @"%(\w+)%")
  .Cast<Match>()
  .GroupBy(m => m.Groups[1].Value)
  .ToDictionary(g => g.Key, g => g.Count());

foreach (KeyValuePair<string,int> key in keys) {
  Console.WriteLine("{0} occurs {1} time(s).", key.Key, key.Value);
}

输出:

x occurs 1 time(s).
y occurs 1 time(s).
于 2012-12-09T15:41:02.750 回答