.NET Regular Expression - Create String?

I have a regular expression that I use to extract two parts of a folder name:

([0-9]{8})_([0-9A-Ba-c]+)_BLAH 

No problems. This will match 12345678_abc_BLAH - I have "12345678" and "abc" in two groups.

Is it possible to create a folder name by providing a method with two lines and inserting them into the template groups?

 public string ConstructFolderName(string firstGroup, string secondGroup, string pattern) { //Return firstGroup_secondGroup_BLAH } 

This would be more manageable using the same template to extract groups and build strings.

+3
c # regex
source share
2 answers

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.

+2
source share
+3
source share

All Articles