在我的程序中,您可以编写一个可以编写变量的字符串.
例如:
我的狗的名字是%x%,他有%y%岁.
我可以替换的是任何一个%%.所以我需要一个函数来告诉我在该字符串中有哪些变量.
GetVariablesNames(string) => result { %x%, %y% }
Run Code Online (Sandbox Code Playgroud)
我会使用正则表达式来查找看起来像变量的任何内容.
如果您的变量是百分号,任意字符,百分号,则以下内容应该有效:
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;
}
Run Code Online (Sandbox Code Playgroud)
MSDN: