簡體   English   中英

C#正則表達式使用匹配值替換

[英]C# Regex Replace using match value

我試圖用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>");

返回一個新字符串,在該字符串中,當前實例中所有出現的指定字符串都被另一個指定字符串替換。

您沒有重新分配給html

所以:

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

在其他答案狀態中,您未分配結果值。

我要補充一點,您的foreach循環沒有多大意義,您可以使用內聯替換:

Regex ItemRegex = new Regex(@"@Html.Partial\(""[a-zA-Z]+""\)", RegexOptions.Compiled);
html = ItemRegex.Replace(html, "<h2>My Partial View</h2>");

這個怎么樣? 這樣,您就可以使用匹配中的值替換為?

但是,最大的問題是您沒有將替換結果重新分配給html變量。

using System;
using System.Text.RegularExpressions;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            var html = @"
                            <h1>This is a Title</h1>
                            @Html.Partial(""MyPartialView"")
                        ";

            var itemRegex = new Regex(@"@Html.Partial\(""([a-zA-Z]+)""\)", RegexOptions.Compiled);
            html = itemRegex.Replace(html, "<h2>$1</h2>");

            Console.WriteLine(html);
            Console.ReadKey();
        }
    }
}

感覺很傻。 該字符串是可變的,因此我需要重新創建它。

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

暫無
暫無

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

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