我有字符串,["02-03-2013#3rd Party Fuel", "-1#Archived", "2#06-23-2013#Newswire"]
,我想将其分解为几个部分。这些字符串以日期和索引键为前缀并包含名称。
我设计了一个RegEx
正确匹配每个键的。但是,如果我想一举匹配索引键、日期键和名称。只找到第一个键。递归组似乎没有像我预期的那样工作。
private const string INDEX_KEY_REGEX = @"(?<index>-?\d+)";
private const string DATE_KEY_REGEX = @"(?<date>(?:0?[1-9]|1[012])-(?:0?[1-9]|[12]\d|3[01])-\d{4})";
private const string KEY_SEARCH_REGEX = @"(?<R>(?:^|(?<=#))({0})#(?(R)))(?<name>.*)";
private string Name = "2#06-23-2013#Newswire"
... = Regex.Replace(
Name,
String.Format(KEY_SEARCH_REGEX, INDEX_KEY_REGEX + "|" + DATE_KEY_REGEX),
"${index}, ${date}, ${name}"
);
// These are the current results for all strings when set into the Name variable.
// Correct Result: ", 02-03-2013, 3rd Party Fuel"
// Correct Result: "-1, , Archived"
// Invalid Result: "2, , 06-23-2013#Newswire"
// Should be: "2, 06-23-2013, Newswire"
敏锐的眼睛能看到我错过的东西吗?
我需要的最终解决方案
事实证明我不需要递归组。我只需要 0 到多个序列。这里是完整的RegEx
。
(?:(?:^|(?<=#))(?:(?<index>-?\d+)|(?<date>(?:0?[1-9]|1[012])-(?:0?[1-9]|[12]\d|3[01])-(\d{2}|\d{4})))#)*(?<name>.*)
并且,分段RegEx
private const string INDEX_REGEX = @"(?<index>-?\d+)";
private const string DATE_REGEX = @"(?<date>(?:0?[1-9]|1[012])-(?:0?[1-9]|[12]\d|3[01])-(\d{2}|\d{4}))";
private const string KEY_WRAPPER_REGEX = @"(?:^|(?<=#))(?:{0})#";
private const string KEY_SEARCH_REGEX = @"(?:{0})*(?<name>.*)";