我正在尝试用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
命名组分钟:
有什么建议吗?
答案 0 :(得分:5)
我相信你想要这样的东西(为了便于阅读而换行):
^
(?<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")
)