如何在 C# 中使用 Regex.Replace 对组匹配值进行 UrlEncode
我在 C# 代码中使用正则表达式,使用 Regex.Replace 匹配某些内容 url。我认为我的模式符合我需要的正确匹配方式。我使用“$1”组值语法来创建新字符串。问题是,我需要对“$1”提供的值进行 UrlEncode。我是否需要循环遍历匹配集合,或者我仍然可以使用 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
*/
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
*/
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Regex.Replace() 具有接受 MatchEvaluator 委托的重载。该委托接受 Match 对象并返回替换字符串。像这样的东西应该适合你想要的。
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.