C#Regex使用匹配值替换

use*_*618 2 c# regex

我试图在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;
}
Run Code Online (Sandbox Code Playgroud)

Set*_*ers 6

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

html = html.Replace(ItemMatch.Value, "<h2>My Partial View</h2>");
Run Code Online (Sandbox Code Playgroud)

返回一个新字符串,其中当前实例中所有出现的指定字符串都替换为另一个指定的字符串.