[英]Revert string.Format
即使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)
是否存在这样的算法,并且可以选择返回一个(甚至所有)可能的参数列表?
这是我的解决方案(仅适用于简单情况!)。 它受到限制,因此无法格式化参数,并且格式字符串中不允许使用方括号( “ {{” ):
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.