还原string.Format

时间:2014-02-11 10:40:03

标签: c# .net

即使如此,string.Format()方法也不是确定性可回复的,我需要一个简单的方法 至少检测给定格式化字符串是否可能是给定格式字符串上的string.Format()的结果的方法。 E.g:

string formattedString = "This is a cool, cool, cool string"
string formatString = "This is a cool, {0} string"

bool IsFormatCandidate(formatString, formattedString) 

是否存在这样的算法,并且可以选择返回一个(甚至所有)可能的参数列表?

1 个答案:

答案 0 :(得分:1)

这是我的解决方案(仅适用于简单的情况!!)。它是有限的,因此无法格式化参数,并且格式字符串中不允许使用括号(“{{”):

public bool IsPatternCandidate(
  string formatPattern, 
  string formattedString, 
  IList<string> arguments)
{
  //Argument checks

  Regex regex = new Regex("{\\d+}");      
  string regexPattern = string.Format("^{0}$", regex.Replace(formatPattern, "(.*)"));
  regex = new Regex(regexPattern);

  if (regex.IsMatch(formattedString))
  {
    MatchCollection matches = regex.Matches(formattedString);
    Match match = matches[0];
    for (int i = 1; i < match.Groups.Count; i++)
    {
      arguments.Add(match.Groups[i].Value);
    }

    return true;
  }

  return false;
}