簡體   English   中英

c#替換大括號內的文本,包括大括號

[英]c# Replace text within curly brackets, including the curly brackets

我正在嘗試替換用大括號括起來的字符串。

如果我使用Regex類提供的Replace方法並且未指定大括號,則會找到並正確替換字符串,但是如果我確實指定大括號,例如: {{FullName}} ,則文本將保留不變。

   var pattern = "{{" + keyValue.Key + "}}";
   docText = new Regex(pattern, RegexOptions.IgnoreCase).Replace(docText, keyValue.Value);

以這個字符串為例

Dear {{FullName}}

我想將其替換為John ,以使文本最終像這樣:

Dear John

如何表達正則表達式,以便找到字符串並正確替換?

如果鍵只是一個字符串,則不需要正則表達式。 只需將“ {{FullName}}”替換為“ John”即可。 例:

string template = "Dear {{FullName}}";
string result = template.Replace("{{" + keyValue.Key + "}}", keyValue.Value);

編輯:解決這不起作用的問題...

以下是一個完整的示例。 您可以在https://dotnetfiddle.net/wnIkvf上運行它

using System;
using System.Text.RegularExpressions;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        var keyValue = new KeyValuePair<string,string>("FullName", "John");
        string docText = "Dear {{FullName}}";
        string result = docText.Replace("{{" + keyValue.Key + "}}", keyValue.Value);
        Console.WriteLine(result);
    }
}

尋找"Dear {{FullName}}""Dear John"嗎?

不是正則表達式解決方案...但這就是我有時更喜歡這樣做的方式。

string s = "Dear {{FullName}}";
// use regex to replace FullName like you mentioned before, then...
s.Replace("{",string.empty);
s.Replace("}",string.empty);
var keyValue = new KeyValuePair<string,string>("FullName", "John");
var pattern = "{{" + keyValue.Key + "}}";
Console.WriteLine(new Regex(Regex.Escape(pattern), RegexOptions.IgnoreCase).Replace("Dear {{FullName}}", keyValue.Value));

輸出:

Dear John

如果您確實想使用正則表達式,請使用Regex.Escape轉義文字文本以將其轉換為正則表達式模式。

var keyValue = new KeyValuePair<string,string>("FullName", "John");
string docText = "Dear {{FullName}}";
var pattern = "{{" + keyValue.Key + "}}";
docText = new Regex(Regex.Escape(pattern), RegexOptions.IgnoreCase).Replace(docText, keyValue.Value);

docText將是Dear John

我相信您真正想做的是替換文檔中的多個內容。

為此,請使用我提供的regex模式,也可以使用regex替換匹配評估程序委托。 這樣做是為了可以針對每個項目主動評估每個匹配項,並根據C#邏輯替換適當的項目。

這是帶有兩個可能的關鍵字設置的示例。

string text = "Dear {{FullName}}, I {{UserName}} am writing to say what a great answer!";

string pattern = @"\{\{(?<Keyword>[^}]+)\}\}";

var replacements 
   = new Dictionary<string, string>() { { "FullName", "OmegaMan" }, { "UserName", "eddy" } };

Regex.Replace(text, pattern, mt =>
{

    return replacements.ContainsKey(mt.Groups["Keyword"].Value)
           ? replacements[mt.Groups["Keyword"].Value]
           : "???";

}
);

結果

親愛的OmegaMan,我正在寫渦流,說這是一個很好的答案!


前面的示例使用

  • 比賽評估人代表
  • 命名匹配捕獲組(?<{Name here}> …)
  • 設置Negation [^ ]表示匹配,直到找到被否定的項為止,在這種情況下為close curl }

暫無
暫無

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

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