-1

Hi all I'm trying to parse css url's with regex but anything fails..

Regex cssUrls = new Regex(@"url\((?<char>['""])?(?<url>.*?)\k<char>?\)");


foreach (var item in cssUrls.Matches("@import url(pepe/global.css);"))
{
    MessageBox.Show(item.ToString());
}

The output is: url(pepe/global.css) but i need that: pepe/global.css

Thanks in advance!

Ben Reich
  • 16,222
  • 2
  • 38
  • 59
SamYan
  • 1,553
  • 1
  • 19
  • 38

2 Answers2

0

The Matches in cssUrls.Matches object holds all of the matched string, therefore item.ToString() gives the whole match. You want something like item.Groups["url"].Value to extract only url named part of the match.

Cemafor
  • 1,633
  • 12
  • 27
  • item doesn't have the "groups" property. – SamYan Jun 17 '13 at 16:57
  • Change your `var` into `Match` in the `foreach` declaration so it knows that `item` will be a `Match`. – Cemafor Jun 17 '13 at 17:00
  • Not a problem, that's what SO is for. It is a little weird that it doesn't detect that item will be a `Match`, I guess its because MatchCollection implements `IEnumerable` and not `IEnumerable`. – Cemafor Jun 17 '13 at 17:04
0

Possible alternative solution, partially implemented with regex and string manipulation.

Regex cssUrls = new Regex(@"\(['"]?(?<url>[^)]+?)['"]?\)");

foreach (var item in cssUrls.Matches("@import url(pepe/global.css);"))
{
    MessageBox.Show(item.TrimStart("(").TrimEnd(")").ToString());
}
HuorSwords
  • 2,225
  • 1
  • 21
  • 34