代码之家  ›  专栏  ›  技术社区  ›  char m

如何编写C#正则表达式模式以匹配基本的printf格式字符串,如“%5.2f”?

  •  3
  • char m  · 技术社区  · 14 年前

    它应符合以下标准(条件部分放在方括号中:

    %[some numbers][.some numbers]d|f|s
    

    符号d | f | s表示其中一个必须在那里。

    谢谢&BR-马蒂

    3 回复  |  直到 14 年前
        1
  •  3
  •   Community CDub    7 年前

    这应该做到:

    string input = "Bloke %s drank %5.2f litres of water and ate %d bananas";
    string pattern = @"%(\d+(\.\d+)?)?(d|f|s)";
    
    foreach (Match m in Regex.Matches(input, pattern))
    {
        Console.WriteLine(m.Value);
    }
    

    我没用 [dfs] 在我的模式中,因为我计划将其更新为使用命名组。这是基于 your earlier question 关于找出C样式格式字符串的替换策略。

    有个主意:

    string input = "Bloke %s drank %5.2f litres of water and ate %d bananas";
    string pattern = @"%(?<Number>\d+(\.\d+)?)?(?<Type>d|f|s)";
    
    int count = 0;
    string result = Regex.Replace(input, pattern, m =>
    {
        var number = m.Groups["Number"].Value;
        var type = m.Groups["Type"].Value;
        // now you can have custom logic to check the type appropriately
        // check the types, format with the count for the current parameter
        return String.Concat("{", count++, "}");
    });
    

    C#/.NET 2.0方法:

    private int formatCount { get; set; }
    
    void Main()
    {
        string input = "Bloke %s drank %5.2f litres of water and ate %d bananas";
        Console.WriteLine(FormatCStyleStrings(input));  
    }
    
    private string FormatCStyleStrings(string input)
    {
        formatCount = 0; // reset count
        string pattern = @"%(?<Number>\d+(\.\d+)?)?(?<Type>d|f|s)";
        string result = Regex.Replace(input, pattern, FormatReplacement);
        return result;
    }
    
    private string FormatReplacement(Match m)
    {
        string number = m.Groups["Number"].Value;
        string type = m.Groups["Type"].Value;
        // custom logic here, format as needed
        return String.Concat("{", formatCount++, "}");
    }
    
        2
  •  2
  •   tchrist    14 年前
    %(?:\d+)?(?:\.\d+)?[dfs]
    

    是你问题的答案,但我怀疑你可能问错了,因为 printf 承认而不是那样。

        3
  •  2
  •   Nico    13 年前

    下面是一个表达式,它匹配printf/scanf函数格式字符串的所有字段。

    (?<!%)(?:%%)*%([\-\+0\ \#])?(\d+|\*)?(\.\*|\.\d+)?([hLIw]|l{1,2}|I32|I64)?([cCdiouxXeEfgGaAnpsSZ])
    

    它基于 Format Fields Specification %[flags][width][.precision][{h|l|ll|L|I|I32|I64|w}]type 匹配组将包含: #1 - flags, #2 - width, #3 - precision, #4 - size prefix, #5 - type.

    取自 here .