【问题标题】:Regex named group problem C#正则表达式命名组问题 C#
【发布时间】:2009-10-09 23:45:00
【问题描述】:

我正在尝试使用 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);
}

返回:

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

有什么建议吗?

【问题讨论】:

  • 您希望它返回什么?抱歉不熟悉 cron 作业...您能否再发布几个示例来说明您将要解析的内容?
  • 在您的示例中,您已经定义了 CronRe,但在循环中您使用的是 LogRe.. 是示例中的拼写错误还是您在那里使用了不同的正则表达式?

标签: c# regex


【解决方案1】:

我相信你想要这样的东西(换行以提高可读性):

^
(?<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")
)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-16
    • 1970-01-01
    • 1970-01-01
    • 2014-11-11
    • 1970-01-01
    • 2011-12-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多