代码之家  ›  专栏  ›  技术社区  ›  polygenelubricants

正则表达式:阶乘

  •  4
  • polygenelubricants  · 技术社区  · 7 年前

    这是StackOverlow的一个实验性新功能:通过解决各种经典问题来锻炼你的正则表达式肌肉。没有一个正确的答案,事实上,我们应该收集尽可能多的正确答案,只要他们提供教育价值。所有口味均可接受,但请清楚记录。尽可能地提供测试用例/代码片段来证明模式“有效”。

    十 阶乘是否使用正则表达式?

    ,它还能找到吗 不 ?

    2 回复  |  直到 15 年前
        1
  •  3
  •   polygenelubricants    16 年前

    see also on ideone.com

    import java.util.regex.*;
    
    class Factorial {
    static String assertPrefix(String pattern) {
       return "(?<=(?=^pattern).*)".replace("pattern", pattern);
    }
    public static void main(String[] args) {
       final Pattern FACTORIAL = Pattern.compile(
          "(?x) (?: inc stepUp)+"
             .replace("inc", "(?=(^|\\1 .))")
             //                      1
    
             .replace("stepUp", "(?: ^. | (?<=(^.*)) (?=(.*)) (?: notThereYet \\2)+ exactlyThere )")
             //                                2          3
    
             .replace("notThereYet", "(?:  (?=((?=\\3) .  |  \\4 .)) (?=\\1(.*)) (?=\\4\\5)  )")
             //                                           4                  5
    
             .replace("exactlyThere", "measure4 measure1")
                .replace("measure4", assertPrefix("\\4(.*)"))
                .replace("measure1", assertPrefix("\\1\\6"))
       );
    
       for (int n = 0; n < 1000; n++) {
          Matcher m = FACTORIAL.matcher(new String(new char[n]));
          if (m.matches()) {
             System.out.printf("%3s = %s!%n", n, m.group(1).length() + 1);
          }
       }
    }
    }
    
        2
  •  1
  •   polygenelubricants    9 年前

    使用.NET平衡组,用C#表示( see also on ideone.com ):

    var r = new Regex(@"(?xn) 
    
    ^(
       (
         ( ^.
         | (?=  (?<temp-n> .)+ )
           (?<= (?<fact>  .+)  )
           (?<n-temp> \k<fact> )+?
           (?(temp) (?!))
         )
         (?<n>)
       )+
     )$
    
    ");
    
    for (int x = 0; x < 6000; x++) {
       Match m = r.Match("".PadLeft(x));
       if (m.Success) {
          Console.WriteLine("{0,4} = {1}! ", x, m.Groups["n"].Captures.Count);
       }
    }
    

    所使用的.NET版本ideone.com公司似乎有一个错误在平衡组,使不情愿的重复 +? + 可能就够了。另请参见: Backtracking a balancing group in a greedy repetition may cause imbalance?

    推荐文章