代码之家  ›  专栏  ›  技术社区  ›  Brian Hicks

正则表达式命名组问题C#

  •  0
  • Brian Hicks  · 技术社区  · 16 年前

    */15 * * * * * http://www.google.com/

    Regex cronRe = new Regex(@"(?<minutes>[\d\*\-,]+) (?<hours>[\d\*\-,]+) (?<days>[\d\*\-,]+) (?<months>[\d\*\-,]+) (?<dotw>[\d\*\-,]+) (?<years>[\d\*\-,]+) (?<command>[\d\*\-,]+)");
    
    //loop through jobs and do them
    for (int i = 0; i < lines.Length; i++)
    {
        Match line = logRe.Match(lines[i]);
        bool runJob = true;
        for (int j = 0; j < line.Groups.Count; j++)
        {
            Console.Write(j.ToString() + ": " + line.Groups[j].Value + "\n");
        }
        Console.Write("named group minutes: " + line.Groups["minutes"].Value);
    }
    

    0: */15 * * * * * http://www.google.com
    1: */15 *
    2.
    4.
    5.
    6. http://www.google.com
    命名组分钟数:

    1 回复  |  直到 16 年前
        1
  •  5
  •   Tomalak    16 年前

    ^
    (?<minutes>[\d*,/-]+)\s
    (?<hours>[\d*,/-]+)\s
    (?<days>[\d*,/-]+)\s
    (?<months>[\d*,/-]+)\s
    (?<dotw>[\d*,/-]+)\s
    (?<years>[\d*,/-]+)\s
    (?<command>.*)
    $
    

    笔记:

    • 你不需要在角色类中逃离明星。

    ([\d*,/-]+)

    (\d+(?:-\d+)?(?:,\d+(?:-\d+)?)*(?:,\*)?|\*(?:/\d+)?)
    

    解释

    (
      \d+                 // matches numbers ("3")
      (?:-\d+)?           // with the above: matches ranges ("3-4")
      (?:                 // optional
        ,\d+              // matches more numbers ("3,6")
        (?:-\d+)?         // matches more ranges ("3,6-9")
      )*                  // allows repeat ("3,6-9,11")
      (?:,\*)?            // allows star at the end ("3,6-9,11,*")
      |                   // alternatively...
      \*(?:/\d+)?         // allows star with optional filter ("*" or "*/15")
    )