无法解析正则表达式中的组

时间:2012-07-14 21:55:37

标签: c# regex

我正在使用下面的正则表达式来匹配以下语句:

  

@import url(normalize.css); @import url(style.css); @进口   URL(helpers.css);

   /// <summary>
   /// The regular expression to search files for.
   /// </summary>
   private static readonly Regex ImportsRegex = new Regex(@"@import\surl\(([^.]+\.css)\);", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.IgnorePatternWhitespace);

这与我的陈述相符,但是当我试图让我的小组退出比赛时,我得到的是完整的结果,而不是我期望的值。

例如预期结果normalize.css     实际结果@import url(normalize.css);

执行此操作的代码如下。谁能告诉我我做错了什么?

    /// <summary>
    /// Parses the string for css imports and adds them to the file dependency list.
    /// </summary>
    /// <param name="css">
    /// The css to parse.
    /// </param>
    private void ParseImportsToCache(string css)
    {
        GroupCollection groups = ImportsRegex.Match(css).Groups;

        // Check and add the @import params to the cache dependancy list.
        foreach (string groupName in ImportsRegex.GetGroupNames())
        {
            // I'm getting the full match here??
            string file = groups[groupName].Value;

            List<string> files = new List<string>();
            Array.ForEach(
                CSSPaths,
                cssPath => Array.ForEach(
                    Directory.GetFiles(
                        HttpContext.Current.Server.MapPath(cssPath),
                        file,
                        SearchOption.AllDirectories),
                    files.Add));

            this.cacheDependencies.Add(new CacheDependency(files.FirstOrDefault()));
        }
    }

3 个答案:

答案 0 :(得分:3)

您应该始终将您的正则表达式表示为您要查找的内容。 (?:exp)用于非捕获组,而()用于捕获组。您也可以为其命名,例如(?<name>exp)

将您的正则表达式更改为(?:@import\surl\()(?<filename>[^.]+\.css)(?:\);)并将其捕获为

pRegexMatch.Groups["filename"].Captures[0].Value.Trim();

希望这有帮助。

此致

答案 1 :(得分:1)

代替群组迭代。你的第二场比赛将是内线比赛。

答案 2 :(得分:0)

您必须像这样确定组名:

Regex.Matches(@"@import\surl\((?<yourGroupname)[^.]+\.css)\);"
相关问题