简体   繁体   English

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

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

I am using a regular expression in my c# code that matches some content urls using Regex.Replace. 我在我的c#代码中使用正则表达式,它使用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. 我使用'$ 1'组值语法来创建新字符串。 The problem is, I need to UrlEncode the value provided by '$1'. 问题是,我需要UrlEncode'$ 1'提供的值。 Do I need to loop through the matches collection or can I still use Regex.Replace? 我是否需要遍历匹配集合,还是仍然可以使用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
*/

Regex.Replace() has an overload that takes in a MatchEvaluator delegate. Regex.Replace()有一个重载,它接受一个MatchEvaluator委托。 This delegate takes in the Match object and returns the replacement string. 该委托接受Match对象并返回替换字符串。 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));
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM