防止 RegEx 中的重复匹配

Ste*_*ane 3 c# regex unique distinct

以下代码

string expression = "(\\{[0-9]+\\})";
RegexOptions options = ((RegexOptions.IgnorePatternWhitespace | RegexOptions.Multiline) | RegexOptions.IgnoreCase);
Regex tokenParser = new Regex(expression, options);

MatchCollection matches = tokenParser.Matches("The {0} is a {1} and the {2} is also a {1}");
Run Code Online (Sandbox Code Playgroud)

将匹配并捕获“{0}”、“{1}”、“{2}”和“{1}”。

是否可以更改它(正则表达式或 RegEx 的选项),以便匹配并捕获“{0}”、“{1}”和“{2}”。换句话说,每场比赛应该只捕获一次?

Ste*_*ane 5

这是我想出的。

private static bool TokensMatch(string t1, string t2)
{
  return TokenString(t1) == TokenString(t2);
}

private static string TokenString(string input)
{
  Regex tokenParser = new Regex(@"(\{[0-9]+\})|(\[.*?\])");

  string[] tokens = tokenParser.Matches(input).Cast<Match>()
      .Select(m => m.Value).Distinct().OrderBy(s => s).ToArray<string>();

  return String.Join(String.Empty, tokens);
}
Run Code Online (Sandbox Code Playgroud)

请注意,正则表达式与我的问题中的正则表达式的不同是由于我迎合了两种类型的令牌;由 {} 分隔的编号和由 [] 分隔的命名;