开发者

How do I UrlEncode a group match value using Regex.Replace in C#

开发者 https://www.devze.com 2023-02-12 11:55 出处:网络
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 synta

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, replace开发者_运维技巧ment);
/*
    text2 output:
    src="/relative/image.ashx?imageUrl=http://www2.domain2.com/servlet/image?id2=123"
    imageUrl param above needs to be url encoded
*/


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));
});
0

精彩评论

暂无评论...
验证码 换一张
取 消