2014-02-11 62 views
0

即使如此string.Format()方法不是確定性可恢復的,我需要一個簡單的 方法,至少檢測給定的格式化字符串是否可以是給定的string.Format()結果給定格式字符串。 例如: -恢復字符串。格式

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

bool IsFormatCandidate(formatString, formattedString) 

這樣的算法存在,可以任選一種(甚至全部)可能的參數列表(S)被退回?

+0

這個問題太廣。這裏沒有任何東西直接來自C庫中的'sscanf'。 – quetzalcoatl

+1

[Parsing formatted string](http://stackoverflow.com/questions/1410012/parsing-formatted-string) – Jimmy

+1

的可能重複考慮一個格式字符串「{0} {1} {2} {3} ...'和一個結果字符串'abcdefg ...'。現在,請享受!所以不可能恢復'String.Format',因爲它是單向票據。 –

回答

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