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?

4
  • This question is too broad. There's nothing here directly like sscanf from C library. Feb 11, 2014 at 10:42
  • 1
    possible duplicate of Parsing formatted string
    – Jimmy
    Feb 11, 2014 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. Feb 11, 2014 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, 2014 at 21:22

1 Answer 1

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;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.