2012-07-14 37 views
0

解析我使用下面的正则表达式匹配下面的语句组:无法从正则表达式

@import URL(normalize.css); @import url(style.css); @import 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); 

这是我的匹配声明,但,当我试图让组了我的比赛,我得到完整的结果,而不是我期待的价值。

e.g预期的结果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())); 
     } 
    } 
+0

你为什么要遍历所有的组时,你只能似乎想的群体之一?这似乎是一种非常复杂的方式来实现你想要的。 – 2012-07-14 21:58:27

+0

我只想要文件的第一个实例。我得到了Directory.GetFiles方法返回的第一个实例。循环有点混乱。你可以责怪Resharper。 – 2012-07-14 22:00:14

回答

3

你应该总是指出你正在寻找的正则表达式。 (?:exp)用于非捕获组,而()用于捕获组。您也可以给他们的名字,像(?<name>exp)

你的正则表达式更改为(?:@import\surl\()(?<filename>[^.]+\.css)(?:\);)并捕捉它像

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

希望这有助于。

问候

+0

向导!这很有用! – 2012-07-14 22:09:22

+1

非常欢迎=) – 2012-07-14 22:09:39

1

而是反复遍历组。你的第二场比赛将是内在的一场比赛。

0

你必须确定的组名这样的:

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