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

Bri*_*cks 0 c# regex

我正在尝试用C#编写带有命名捕获的正则表达式来解析cron作业.但问题是,使用单引号和括号命名捕获组时,值都返回空白.例如,输入

*/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);
}
Run Code Online (Sandbox Code Playgroud)

回来这个:

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

有什么建议?

Tom*_*lak 5

我相信你想要这样的东西(为了便于阅读而换行):

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

笔记:

  • 表达式必须正确锚定(至少"^").
  • 破折号在字符类中具有特殊含义(它创建范围).如果要匹配文字短划线,请将其放在字符类的末尾.
  • 您不需要在角色类中逃脱星形.

除此之外:表达式([\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")
)
Run Code Online (Sandbox Code Playgroud)