我有一个正则表达式,用于提取文件夹名称的两个部分:
([0-9]{8})_([0-9A-Ba-c]+)_BLAH
Run Code Online (Sandbox Code Playgroud)
没问题。这将匹配 12345678_abc_BLAH - 我有“12345678”和“abc”分为两组。
是否可以通过提供带有两个字符串的方法并将它们插入到模式组中来构造文件夹名称?
public string ConstructFolderName(string firstGroup, string secondGroup, string pattern)
{
//Return firstGroup_secondGroup_BLAH
}
Run Code Online (Sandbox Code Playgroud)
使用相同的模式来提取组和构造字符串会更容易管理。
如果您知道您的正则表达式将始终有两个捕获组,那么您可以对正则表达式进行正则表达式,可以这么说。
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);
}
Run Code Online (Sandbox Code Playgroud)
显然,这没有任何错误检查,并且使用 String.Replace 之外的其他方法可能会更好;但是,这确实有效,并且应该会给您一些想法。
编辑:一个明显的改进是在构造firstGroup和字符串之前实际使用该模式来验证它们。secondGroup的MatchCollection0 和 1 项可以创建自己的正则表达式并在那里执行匹配。如果你愿意的话我可以补充一下。
EDIT2:这是我正在谈论的验证:
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);
}
Run Code Online (Sandbox Code Playgroud)
另外,我可能会补充一点,您可以将第二个捕获组更改为,([0-9ABa-c]+)因为 A 到 B 并不是真正的范围。