在我的程序中,你可以编写一个字符串,其中可以写入变量。
例如:
我狗的名字是 %x%,它今年 %y% 岁了。
可以被替换的单词位于 %%
之间。因此,我需要一个函数来告诉我在该字符串中有哪些变量。
GetVariablesNames(string) => result { %x%, %y% }
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:
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).
%(\w*)%
也会匹配零字符变量,即%%
。 - Guffa+
,它表示一个或多个。 - Jonathon Reinhart