.NET正则表达式 – 创建字符串?

我有一个正则表达式,我用它来提取文件夹名称的两个部分:

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

没问题。 这将匹配12345678_abc_BLAH – 我有两组“12345678”和“abc”。

是否可以通过提供具有两个字符串的方法并将它们插入模式组来构造文件夹名称?

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

使用相同的模式提取组和构造字符串将更易于管理。

如果你知道你的正则表达式将总是有两个捕获组,那么你可以正则表达正则表达式,可以这么说。

 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); } 

显然,这没有任何错误检查,并且可能使用String.Replace之外的其他方法更好地完成; 但是,这肯定有效,应该给你一些想法。

编辑 :一个明显的改进是在构造它们之前实际使用模式来validationfirstGroupsecondGroup字符串。 MatchCollection的0和1项可以创建自己的Regex并在那里执行匹配。 我可以补充说,如果你想。

EDIT2 :这是我正在谈论的validation:

 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); } 

另外,我可以补充一点,您可以将第二个捕获组更改为([0-9ABa-c]+)因为A到B实际上不是一个范围。

你想使用String.Format ?

String.Format方法(String,Object [])