I have the strings, ["02-03-2013#3rd Party Fuel", "-1#Archived", "2#06-23-2013#Newswire"]
, which I want to break down into several parts. These strings are prefixed with date and index keys and contain a name.
I've design a RegEx
that matches each key properly. However, if I want to match the index key, date key, and name in fell swoop. Only the first key is found. It seems the recursive group isn't working as I expect it should.
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"
Does a keen eye see something I've missed?
Final Solution As I Needed It
It turns out I didn't need a recursive group. I simply needed 0 to many sequence. Here is the full RegEx
.
(?:(?:^|(?<=#))(?:(?<index>-?\d+)|(?<date>(?:0?[1-9]|1[012])-(?:0?[1-9]|[12]\d|3[01])-(\d{2}|\d{4})))#)*(?<name>.*)
And, the segmented 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>.*)";