簡體   English   中英

用於替換標簽的正則表達式

[英]Regex for replacing tags

我需要像這樣替換字符串

@@colored:some_text @color:clr@@

使用以下html標記:

<p style='color:clr;'>some_text</P>

我寫了一個正則表達式來搜索這樣的文本片段,但我不知道怎么做替換。 是我的正則表達式的一個例子

以下是我嘗試執行此操作的C#代碼示例

    private string Colored(string data)
    {
        var colorMatches = Regex.Matches(data, "@@colored:(.|\n)*? @color:(.*?)@@");
        if (colorMatches.Count == 0)
            return data;

        var sb = new StringBuilder();

        var matches = new List<Match>();
        sb.Append(Regex.Replace(data, @"@@colored:(.|\n)*? @color:(.*?)@@", match =>
        {
            // i don't know how to replace text properly
        }));

        return sb.ToString();
    }

請幫我做文字替換。 先感謝您!

Regex.Replace允許您使用$<number>語法來引用捕獲正則表達式中定義的捕獲的值以進行替換。 您對Replace調用如下所示:

Regex.Replace(
    data
,   @"@@colored:((?:.|\n)*?) @color:(.*?)@@"
,   @"<p style='$2;'>$1</p>"
)

$2指的是(.*?)捕獲組的內容; $1指的是((?:.|\\n)*?) 請注意使用非捕獲括號(?: ...)進行分組而不創建捕獲組。 但是,由於回溯 ,這可能導致顯着的減速,因此您需要非常小心。 有關處理問題的方法,請參閱此文章

您需要將延遲點匹配子模式放入第一個捕獲組(第一組非轉義括號):

(?s)@@colored:(.*?) @color:(.*?)@@

請注意. 要匹配換行符,您需要使用單行修飾符 (內聯(?s)RegexOptions.Singleline標志)。

並使用<p style='color:$2;'>$1</p>替換,其中$1表示some_text$2表示color

查看正則表達式演示 ,這是一個IDEONE演示

var str = "some text @@colored:South Africa, officially the Republic of South Africa, is the southernmost country in Africa. It is bounded on the south by 2,798 kilometers of coastline of southern Africa stretching along the South Atlantic and Indian Oceans on the north by the neighbouring countries of Namibia, Botswana and Zimbabwe, and on the east by Mozambique and Swaziland, and surrounding the kingdom of Lesotho.[12] South Africa is the 25th-largest country in the world by land area, and with close to 53 million people, is the world's 24th-most populous nation. @color:red@@ another text";
Console.WriteLine(Regex.Replace(str, @"(?s)@@colored:(.*?) @color:(.*?)@@", "<p style='color:$2;'>$1</p>"));

我通常的警告 :懶惰點匹配可能會導致代碼執行凍結,輸入非常大。 要避免它,請使用unroll-the-loop技術:

@@colored:([^ ]*(?: (?!@color:)[^ ]*)*) @color:([^@]*(?:@(?!@)[^@]*)*)@@

此正則表達式還有另一個優點 :它不需要單行修飾符來匹配換行符號。 請參閱正則表達式#2

暫無
暫無

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

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