簡體   English   中英

無法解析來自正則表達式的組

[英]Cannot parse groups from regex

我正在使用下面的正則表達式來匹配以下語句:

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

這與我的陳述相符,但是當我試圖使組脫離匹配時,我得到的是完整結果,而不是我期望的值。

例如預期結果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()));
        }
    }

您應該始終將正則表達式表示為要查找的內容。 (?:exp)用於非捕獲組,而()用於捕獲組。 您也可以給他們起名字,例如(?<name>exp)

將您的Regex更改為(?:@import\\surl\\()(?<filename>[^.]+\\.css)(?:\\);)並捕獲它

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

希望這可以幫助。

問候

而是遍歷組。 您的第二場比賽將是內部比賽。

您必須像這樣確定組名:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM