代码之家  ›  专栏  ›  技术社区  ›  youwhut

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

  •  3
  • youwhut  · 技术社区  · 14 年前

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

    ([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
    
    }
    

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

    2 回复  |  直到 14 年前
        1
  •  2
  •   Shibumi    14 年前

    如果您知道您的regex将始终有两个捕获组,那么可以这么说,您可以对regex进行regex。

    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;但是,这确实有效,应该会给您一些建议。

    编辑 :一个明显的改进是实际使用模式来验证 firstGroup secondGroup 在你构造它们之前。这个 MatchCollection 的0和1项可以创建自己的Regex并在那里执行匹配。如果你愿意的话,我可以加上。

    编辑2 :以下是我所说的验证:

    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实际上不是一个范围。