How do I UrlEncode a group match value using Regex.Replace in C# -
i using regular expression in c# code matches content urls using regex.replace. think have pattern way need match correctly. using '$1' group value syntax create new string. problem is, need urlencode value provided '$1'. need loop through matches collection or can still use regex.replace? help.
regex regex = new regex(@"src=""(.+?/servlet/image.+?)"""); // value of $1 needs 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 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 url encoded */
regex.replace() has overload takes in matchevaluator delegate. delegate takes in match object , returns replacement string. should work want.
regex.replace(text, delegate(match match) { return string.format(@"src=""/relative/image.ashx?imageurl={0}""", httputility.urlencode(match.groups[1].value)); });
Comments
Post a Comment