0

I am using a regular expression in my c# code that matches some content urls using Regex.Replace. I think I have the pattern the way I need it to match correctly. I am using the '$1' group value syntax to create the new string. The problem is, I need to UrlEncode the value provided by '$1'. Do I need to loop through the matches collection or can I still use Regex.Replace? Thanks for your help.

Regex regex = new Regex(@"src=""(.+?/servlet/image.+?)""");

// value of $1 needs to be Url Encoded!
string replacement = @"src=""/relative/image.ashx?imageUrl=$1""";
string text1 = @"src=""http://www.domain1.com/servlet/image?id=abc""";
string text2 = @"src=""http://www2.domain2.com/servlet/image?id2=123""";
text1 = regex.Replace(text1, replacement);
/*
    text1 output:
    src="/relative/image.ashx?imageUrl=http://www.domain1.com/servlet/image?id=abc"
    imageUrl param above needs to be url encoded
*/

text2 = regex.Replace(text2, replacement);
/*
    text2 output:
    src="/relative/image.ashx?imageUrl=http://www2.domain2.com/servlet/image?id2=123"
    imageUrl param above needs to be url encoded
*/
fehays
  • 3,147
  • 1
  • 24
  • 43
  • hmmm, why do I have the strange feeling that you are using regex for more than parsing urls like parsing HTML. The first is bad, the second is, well, I think @bobince has the right words to explain it http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454: – Darin Dimitrov Feb 18 '11 at 18:23
  • Thanks for that. That was funny :). Yes I am parsing html, but it falls more into the category of the answer directly below the one you linked. I'm know enough to understand this is a crappy way to do it, but I'm integrating something and there's not much choice. – fehays Feb 18 '11 at 18:59

1 Answers1

2

Regex.Replace() has an overload that takes in a MatchEvaluator delegate. This delegate takes in the Match object and returns the replacement string. Something like this should work for what you want.

regex.Replace(text, delegate(Match match)
{
    return string.Format(@"src=""/relative/image.ashx?imageUrl={0}""", HttpUtility.UrlEncode(match.Groups[1].Value));
});
Brian Reichle
  • 2,798
  • 2
  • 30
  • 34