簡體   English   中英

如何使用C#中的Regex.Replace對組匹配值進行UrlEncode

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

我在我的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
*/

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM