如何使用C#中的Regex.Replace对组匹配值进行UrlEncode

时间:2011-02-18 18:20:29

标签: c# regex pattern-matching urlencode

我在我的c#代码中使用正则表达式,它使用Regex.Replace匹配某些内容网址。我想我的模式正是我需要它才能正确匹配的方式。我使用'$ 1'组值语法来创建新字符串。问题是,我需要UrlEncode'$ 1'提供的值。我是否需要遍历匹配集合,还是仍然可以使用Regex.Replace?谢谢你的帮助。

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
*/

1 个答案:

答案 0 :(得分:2)

Regex.Replace()有一个重载,它接受一个MatchEvaluator委托。该委托接受Match对象并返回替换字符串。这样的事情应该适合你想要的东西。

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