尽管如此,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) 这样的算法是否存在,并且可以选择地返回一个(甚至所有)可能的参数列表?
发布于 2014-02-11 10:42:40
这是我的解决方案(只适用于简单的案例!)它是有限的,因此不能格式化参数,格式字符串中不允许使用方括号("{{"):
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;
}https://stackoverflow.com/questions/21699504
复制相似问题