tags:

views:

79

answers:

1

Hi,

Can I ask for a pointer re C# and Regex. I've got the routine that works ok below that finds links within CSS. If I wanted to rewrite the links I find as I go through, and then have a copy of a string at the end of this that represents the initial CSS text but with the rewritten links in place how would I do this?

    var resultList = new List<Uri>();
    string cssText = new WebClient().DownloadString(uri.ToString());
    MatchCollection matches = Regex.Matches(cssText, @"url\(('|"")?([^']*?)('|"")?\)", RegexOptions.IgnoreCase);
    foreach (Match match in matches)
    {
        var groups = match.Groups;
        var relUrl = groups[2].ToString();
        var itemUri = new Uri(uri, relUrl);
        // WANT TO CHANGE / REWRITE THE URI HERE 
        resultList.Add(itemUri);
    }
    // WANT TO HAVE ACCESS TO AN UPDATED "cssText" HERE THAT INCLUDES THE REWRITTEN LINKS

thanks

PS. The catch is I need to be able to pass the URL segment I find (i.e. in capture group 2, for which in "Regex.Replace" I would refer to as $2), to a function to work out the replacement string. I don't seem to be able to do this within with this approach:

Regex.Replace(cssText, regexStr, @"url($1" + fn("$2") + @"$3)") //DOES NOT SEEM TO WORK

Any ideas?

+2  A: 

Use Regex.Replace, It may be something like this.

cssText = Regex.Replace(cssText, @"(url\(['""]?)(.*?)(['""]?\))", "$1"+uri+"$2$3");

I am not sure what value are in the variable uri though

S.Mark
thanks - I'll try it
Greg
does not quite work - I need to be able to call a function to work out the replacement string that I want to use, it seems I can't put this function within the "Regex.Replace" call and use "$2" as a parameter to the function - any ideas?
Greg
may I know what fn() do?
S.Mark
or you can use delegate, call fn() inside that, `cssText = Regex.Replace(cssText, regexStr, delegate(Match m) {return m.Groups[1].Value + fn(m.Groups[2].Value) + m.Groups[3].Value; });`
S.Mark
or in C# 3.0 >, you could use Lambda, `cssText = Regex.Replace(cssText, regexStr, m => m.Value[1] + fn(m.Value[2]) + m.Value[3]);`, I dont have C# 3.0 > now, so Lambda code is not tested.
S.Mark
excellent thanks
Greg