【问题标题】:RegEx: fetch number of decimal places from DisplayFormat stringRegEx:从 DisplayFormat 字符串中获取小数位数
【发布时间】:2012-12-17 13:48:51
【问题描述】:

任何人都可以帮助创建一个正则表达式来处理这种情况。 数值有一个显示格式字符串,可以是以下格式 正值格式;负值格式。 正负格式可以是例如 '#,##0.00;(#,##0.0000)' 或 '#,##0;(#,##0.0)' 或 '#,##0' - 这意味着一个正值应该在点后显示 2 个数字,另一个 - 没有数字。

所以我需要创建正则表达式来处理这 3 种情况,正值和\或负值的小数位数是多少。

'#,##0.00;(#,##0.0000)' -> 2, 4
'#,##0;(#,##0.0)' -> 0, 1
'#,##0' -> 0

我发现了以下问题,但没有得到解答或使用解析字符串而不是 RegExp - What would be a good way of determining number of decimal places from a format string?identify the number of decimal places based on the format string

【问题讨论】:

  • “句柄”是什么意思?提取数字?
  • 我需要知道 count 个正负值的小数位数:'#,##0.00;(#,##0.0000)' - #,## 0.00 是 DisplayFormat 的正值部分,我应该得到 2 作为组 Positive 的输出;然后是 poz i 负部分之间的分隔符';'然后变为(或不变为)负数,带括号 - (#,##0.0000),因此输出(小数位数)为四。

标签: .net regex


【解决方案1】:

这适用于所有 3 个提供的字符串

        string pat = "#,##([0-9]([0-9.]*?|$))($|;[(]#,##[0-9]([0-9.]*?)[)])";
        Match m = Regex.Match(input, pat);

        int lengthA = m.Result("$2").Replace(".", "").Length;
        if (!String.IsNullOrWhiteSpace(m.Result("$4")))
        {
            int lengthB = m.Result("$4").Replace(".", "").Length;
        }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-11-11
    • 1970-01-01
    • 2018-05-19
    • 1970-01-01
    • 2017-05-02
    • 1970-01-01
    • 2020-06-10
    相关资源
    最近更新 更多