gpt4 book ai didi

C# 正则表达式使用匹配值替换

转载 作者:行者123 更新时间:2023-12-04 12:27:01 30 4
gpt4 key购买 nike

我正在尝试用 C# 编写一个函数,用自定义字符串替换所有出现的正则表达式模式。我需要使用匹配字符串来生成替换字符串,所以我试图循环匹配而不是使用 Regex.Replace()。当我调试我的代码时,正则表达式模式匹配我的 html 字符串的一部分并进入 foreach 循环,但是,string.Replace 函数不会替换匹配项。有谁知道是什么导致这种情况发生?

我的功能的简化版本:-

public static string GetHTML() {
string html = @"
<h1>This is a Title</h1>
@Html.Partial(""MyPartialView"")
";

Regex ItemRegex = new Regex(@"@Html.Partial\(""[a-zA-Z]+""\)", RegexOptions.Compiled);
foreach (Match ItemMatch in ItemRegex.Matches(html))
{
html.Replace(ItemMatch.Value, "<h2>My Partial View</h2>");
}

return html;
}

最佳答案

string.Replace返回一个字符串值。您需要将此分配给您的 html 变量。请注意,它还替换了匹配值的所有匹配项,这意味着您可能不需要循环。

html = html.Replace(ItemMatch.Value, "<h2>My Partial View</h2>");

Returns a new string in which all occurrences of a specified string in the current instance are replaced with another specified string.

关于C# 正则表达式使用匹配值替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12624669/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com