【问题标题】:Convert a TimeSpan Formatstring to an InputMask将 TimeSpan 格式字符串转换为 InputMask
【发布时间】:2014-01-08 15:05:45
【问题描述】:

我有一个 TimeSpan 具有自定义格式,如 @"hh\:mm\:ss\.fff",并希望使用来自 xceed (https://wpftoolkit.codeplex.com/wikipage?title=MaskedTextBox&referringTitle=Home) 的 MaskedTextBox 来帮助用户输入有效的时间跨度。

现在我将FormatString-Property 转换为这样的输入掩码

public string InputMask
{
  get
  {
    string mask = FormatString.Replace('h', '0');
    mask = mask.Replace('m', '0');
    mask = mask.Replace('s', '0');
    mask = mask.Replace('f', '0');
    mask = mask.Replace('d', '0');
    return mask;
  }
}

如果 FormatString 获得另一种我还不知道的格式,则此解决方案看起来很丑陋且不可维护。有没有更优雅的解决方案(例如,使用正则表达式替换),用0 替换任何字母?

【问题讨论】:

  • This ?但我会选择for(int i = 0; i < mask.Length; i++) if(char.IsLetter(mask[i])) mask[i] = '0';
  • 这不起作用,因为mask[i] 没有设置器,而字符串是不可变的。
  • 然后我会来到stackoverflow并在这里发布我的问题=D
  • 任何字母正则表达式:[a-zA-Z]

标签: c# regex replace


【解决方案1】:

这应该可以解决问题:

//using System.Text.RegularExpressions;

string input = @"hh\:mm\:ss\.fff"; //i suppose it's FormatString in your case, don't know the MaskedTextBox
string output = Regex.Replace(input, "[a-zA-Z]","0");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-12-21
    • 1970-01-01
    • 1970-01-01
    • 2023-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多