Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>If you know that your regex will always have two capturing groups, then you can regex the regex, so to speak.</p> <pre><code>private Regex captures = new Regex(@"\(.+?\)"); public string ConstructFolderName(string firstGroup, string secondGroup, string pattern) { MatchCollection matches = captures.Matches(pattern); return pattern.Replace(matches[0].Value, firstGroup).Replace(matches[1].Value, secondGroup); } </code></pre> <p>Obviously this doesn't have any error checking and might be better done with some other method than String.Replace; but, this certainly works and should give you some ideas.</p> <p><strong>EDIT</strong>: An obvious improvement would be to actually use the pattern to validate the <code>firstGroup</code> and <code>secondGroup</code> strings before you construct them. The <code>MatchCollection</code>'s 0 and 1 item could create their own Regex and perform a match there. I can add that if you want.</p> <p><strong>EDIT2</strong>: Here's the validation I was talking about:</p> <pre><code>private Regex captures = new Regex(@"\(.+?\)"); public string ConstructFolderName(string firstGroup, string secondGroup, string pattern) { MatchCollection matches = captures.Matches(pattern); Regex firstCapture = new Regex(matches[0].Value); if (!firstCapture.IsMatch(firstGroup)) throw new FormatException("firstGroup"); Regex secondCapture = new Regex(matches[1].Value); if (!secondCapture.IsMatch(secondGroup)) throw new FormatException("secondGroup"); return pattern.Replace(firstCapture.ToString(), firstGroup).Replace(secondCapture.ToString(), secondGroup); } </code></pre> <p>Also, I might add that you can change the second capturing group to <code>([0-9ABa-c]+)</code> since A to B isn't really a range.</p>
 

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