【问题标题】:Revert string.Format恢复字符串.Format
【发布时间】:2014-02-12 05:23:43
【问题描述】:

即便如此 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) 

这样的算法是否存在并且可以选择返回一个(甚至所有)可能的参数列表?

【问题讨论】:

  • 这个问题太笼统了。这里没有像 C 库中的 sscanf 这样直接的东西。
  • Parsing formatted string的可能重复
  • 考虑格式字符串{0}{1}{2}{3}... 和结果字符串abcdefg...。现在,请尽情享受吧!所以不可能恢复String.Format,因为这是一张单程票。
  • 目前的形式可以回答这个问题。而且我不明白为什么这是“离题”,它清楚地描述了问题,而 StefanG 已尝试解决它?

标签: c# .net


【解决方案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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-05
    • 2014-11-25
    • 2016-10-26
    • 1970-01-01
    • 2014-07-12
    • 1970-01-01
    • 2016-06-05
    • 2020-10-03
    相关资源
    最近更新 更多