I am using the regex below to match the following statements:
@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);
This is matching my statements but when I am trying to get the groups out of my match I am getting the full result rather than the value I am expecting.
e.g expected result normalize.css
actual result @import url(normalize.css);
The code to do this is below. Can anyone tell me what I am doing wrong?
/// <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()));
}
}
You should always denote your Regex to what you are looking for.
(?:exp)is for non-capturing groups, while()is for capturing groups. You can also give them names, like(?<name>exp)Change your Regex to
(?:@import\surl\()(?<filename>[^.]+\.css)(?:\);)and capture it likeHope this helps.
Regards