Note that there are some explanatory texts on larger screens.

plurals
  1. PORecursive RegEx to match keys and name
    primarykey
    data
    text
    <p>I have the strings, <code>["02-03-2013#3rd Party Fuel", "-1#Archived", "2#06-23-2013#Newswire"]</code>, which I want to break down into several parts. These strings are prefixed with date and index keys and contain a name.</p> <p>I've design a <code>RegEx</code> 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.</p> <pre><code>private const string INDEX_KEY_REGEX = @"(?&lt;index&gt;-?\d+)"; private const string DATE_KEY_REGEX = @"(?&lt;date&gt;(?:0?[1-9]|1[012])-(?:0?[1-9]|[12]\d|3[01])-\d{4})"; private const string KEY_SEARCH_REGEX = @"(?&lt;R&gt;(?:^|(?&lt;=#))({0})#(?(R)))(?&lt;name&gt;.*)"; 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" </code></pre> <p>Does a keen eye see something I've missed?</p> <hr> <p><strong>Final Solution As I Needed It</strong></p> <p>It turns out I didn't need a recursive group. I simply needed 0 to many sequence. Here is the full <code>RegEx</code>.</p> <pre><code>(?:(?:^|(?&lt;=#))(?:(?&lt;index&gt;-?\d+)|(?&lt;date&gt;(?:0?[1-9]|1[012])-(?:0?[1-9]|[12]\d|3[01])-(\d{2}|\d{4})))#)*(?&lt;name&gt;.*) </code></pre> <p>And, the segmented <code>RegEx</code></p> <pre><code>private const string INDEX_REGEX = @"(?&lt;index&gt;-?\d+)"; private const string DATE_REGEX = @"(?&lt;date&gt;(?:0?[1-9]|1[012])-(?:0?[1-9]|[12]\d|3[01])-(\d{2}|\d{4}))"; private const string KEY_WRAPPER_REGEX = @"(?:^|(?&lt;=#))(?:{0})#"; private const string KEY_SEARCH_REGEX = @"(?:{0})*(?&lt;name&gt;.*)"; </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload