简体   繁体   English

c#替换大括号内的文本,包括大括号

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

I'm trying to replace a string,enclosed in curly brackets. 我正在尝试替换用大括号括起来的字符串。

If I use the Replace method provided by the Regex class and I don't specify the curly brackets, the string is found and replaced correctly, but if I do specify the curly brackets like this: {{FullName}} , the text is left untouched. 如果我使用Regex类提供的Replace方法并且未指定大括号,则会找到并正确替换字符串,但是如果我确实指定大括号,例如: {{FullName}} ,则文本将保留不变。

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

Take this string as a example 以这个字符串为例

Dear {{FullName}}

I want to replace it with John , so that the text ends up like this: 我想将其替换为John ,以使文本最终像这样:

Dear John . Dear John

How can I express the regex, so that the string is found and replace correctly? 如何表达正则表达式,以便找到字符串并正确替换?

You don't need a regular expression if the key is just a string. 如果键只是一个字符串,则不需要正则表达式。 Just replace "{{FullName}}" with "John". 只需将“ {{FullName}}”替换为“ John”即可。 example: 例:

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

Edit: addressing concerns that this doesn't work... 编辑:解决这不起作用的问题...

The following is a complete example. 以下是一个完整的示例。 You can run it at https://dotnetfiddle.net/wnIkvf 您可以在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);
    }
}

Looking for "Dear {{FullName}}" to "Dear John" ? 寻找"Dear {{FullName}}""Dear John"吗?

not a regex solution... but this is how I prefer to do it sometimes. 不是正则表达式解决方案...但这就是我有时更喜欢这样做的方式。

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));

Output: 输出:

Dear John

If you actually want to use a regular expression, then escape your literal text to turn it into a regular expression pattern using Regex.Escape . 如果您确实想使用正则表达式,请使用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 will be Dear John docText将是Dear John

What I believe is that you really want to do is replace multiple things in a document. 我相信您真正想做的是替换文档中的多个内容。

To do so use the regex pattern I provide, but also use the regex replace match evaluator delegate. 为此,请使用我提供的regex模式,也可以使用regex替换匹配评估程序委托。 What that does, is that every match can be actively evaluated for each item and a proper item will be replaced as per C# logic. 这样做是为了可以针对每个项目主动评估每个匹配项,并根据C#逻辑替换适当的项目。

Here is an example with two possible keywords setup. 这是带有两个可能的关键字设置的示例。

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]
           : "???";

}
);

Result 结果

Dear OmegaMan, I eddy am writing to say what a great answer! 亲爱的OmegaMan,我正在写涡流,说这是一个很好的答案!


The preceding example uses 前面的示例使用

  • Match Evaluator Delegate 比赛评估人代表
  • Named match capture groups (?<{Name here}> …) 命名匹配捕获组(?<{Name here}> …)
  • Set Negation [^ ] which says match until the negated item is found, in this case a closing curly } . 设置Negation [^ ]表示匹配,直到找到被否定的项为止,在这种情况下为close curl }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM