3
我正在使用下面的代码来递归地解析css @import
语句来加载嵌套的css文件在minifer中。虽然这与标准的@import
声明完美配合,但它会错误地将@import
声明添加到媒体查询中,而无需在它们周围创建条件。处理多个正则表达式组
我需要做的是:
- 依次通过我的比赛抓住
filename
组捕获 - 检查相应的
media
组 - 如果是这样的情况下,包裹里面的整个加载CSS使用捕获的参数进行媒体查询
- 如果没有,只需添加文件名捕获内容。
e.g
@import url(style.css) screen and (min-width: 768px);
成为
@media screen and (min-width: 767px) {
/* contents of style.css */
}
我的正则表达式,我使用捕捉到语句是这样的:
(?:@import\surl\()(?<filename>[^.]+\.css)(?:\)((?<media>[^;]+);|;))
这是正确的捕捉。我只是不知道Regex
课程全力以赴。
有人比我更聪明吗?
我的原始代码。
/// <summary>
/// Parses the string for css imports and adds them to the
/// file dependency list.
/// </summary>
/// <param name="css">
/// The css to parse for import statements.
/// </param>
/// <param name="minify">
/// Whether or not the local script should be minified.
/// </param>
/// <returns>The css file parsed for imports.</returns>
private string ParseImportsAndCache(string css, bool minify)
{
// Check for imports and parse if necessary.
if (!css.Contains("@import", StringComparison.OrdinalIgnoreCase))
{
return css;
}
// Recursivly parse the css for imports.
foreach (Match match in ImportsRegex.Matches(css))
{
// Recursivly parse the css for imports.
GroupCollection groups = match.Groups;
// Check and add the @import params to the cache dependancy list.
foreach (var groupName in groups["filename"].Captures)
{
// Get the match
List<string> files = new List<string>();
Array.ForEach(
CSSPaths,
cssPath => Array.ForEach(
Directory.GetFiles(
HttpContext.Current.Server.MapPath(cssPath),
groupName.ToString(),
SearchOption.AllDirectories),
files.Add));
string file = files.FirstOrDefault();
string thisCSS = string.Empty;
// Read the file.
if (file != null)
{
using (StreamReader reader = new StreamReader(file))
{
// Recursiveley parse the css.
thisCSS = this.ParseImportsAndCache(reader.ReadToEnd(),
minify);
}
}
// Replace the regex match with the full qualified css.
css = css.Replace(match.Value, thisCSS);
if (minify)
{
this.cacheDependencies
.Add(new CacheDependency(files.FirstOrDefault()));
}
}
}
return css;
}
您可以像获取文件名一样访问此结果。你有没有尝试过调用'groups [“media”]。捕获'? – 2012-07-24 20:04:15
我是个白痴。我误解了我自己的代码。我实际上并不需要循环组。干杯! (@ [^。] + \ .css)\)(? [^;] *);' –
2012-07-24 21:35:39
)您是不是欢迎=) – 2012-07-24 21:40:11