If you know that your regex will always have two capture groups, then you can regex regular expression.
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); }
Obviously, this does not check for errors and can be better done with a method other than String.Replace; but it certainly works and should give you some ideas.
EDIT . An obvious improvement would be to use a template to check the firstGroup and secondGroup before creating them. MatchCollection elements 0 and 1 can create their own Regex and perform matching there. I can add this if you want.
EDIT2 : here is the validation I talked about:
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); }
In addition, I can add that you can change the second capture group to ([0-9ABa-c]+) , since A to B is not a range.
Shibumi
source share