0

Even so the string.Format() method is not deterministically revertable, I need a simple method that at minimum detects if a given formatted string could be the result of a string.Format() on a given format string. E.g.:

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

bool IsFormatCandidate(formatString, formattedString) 

Does such an algorithm exist and could optionally one (or even all) possible argument list(s) be returned?

StefanG
  • 1,234
  • 2
  • 22
  • 46
  • This question is too broad. There's nothing here directly like `sscanf` from C library. – quetzalcoatl Feb 11 '14 at 10:42
  • 1
    possible duplicate of [Parsing formatted string](http://stackoverflow.com/questions/1410012/parsing-formatted-string) – Jimmy Feb 11 '14 at 10:58
  • 1
    Consider a format string `{0}{1}{2}{3}...` and a result string `abcdefg...`. And now, please enjoy! So it's impossible to revert `String.Format` since it's a one-way ticket. – Tim Schmelter Feb 11 '14 at 12:14
  • In the current form this question can be answered. And I don't see why this is 'off-topic', it clearly describes the problem, and StefanG has tried to solve it? – Ishtar Feb 11 '14 at 21:22

1 Answers1

1

This is my solution (for simple cases only!!). It is limited so that arguments can't be formatted, and no brackets ("{{") are allowed in format string:

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;
}
StefanG
  • 1,234
  • 2
  • 22
  • 46