C#字符串替换为字典

RaY*_*ell 31 c# string dictionary replace

我有一个字符串,我需要做一些替换.我有一个Dictionary<string, string>我定义的搜索替换对的地方.我创建了以下扩展方法来执行此操作:

public static string Replace(this string str, Dictionary<string, string> dict)
{
    StringBuilder sb = new StringBuilder(str);

    return sb.Replace(dict).ToString();
}

public static StringBuild Replace(this StringBuilder sb, 
    Dictionary<string, string> dict)
{
    foreach (KeyValuePair<string, string> replacement in dict)
    {
        sb.Replace(replacement.Key, replacement.Value);
    }

    return sb;
}
Run Code Online (Sandbox Code Playgroud)

有没有更好的方法呢?

Mar*_*ell 45

如果数据被标记化(即"亲爱的$ name $,从$ date $你的余额是$ amount $"),那么a Regex可能是有用的:

static readonly Regex re = new Regex(@"\$(\w+)\$", RegexOptions.Compiled);
static void Main() {
    string input = @"Dear $name$, as of $date$ your balance is $amount$";

    var args = new Dictionary<string, string>(
        StringComparer.OrdinalIgnoreCase) {
            {"name", "Mr Smith"},
            {"date", "05 Aug 2009"},
            {"amount", "GBP200"}
        };
    string output = re.Replace(input, match => args[match.Groups[1].Value]);
}
Run Code Online (Sandbox Code Playgroud)

但是,如果没有这样的东西,我希望你的Replace循环可能与你能做的一样多,而不会达到极限.如果没有标记化,也许可以对其进行分析; 是Replace实际上是一个问题吗?

  • 如果找不到密钥,这将引发异常。 (2认同)
  • @Phoenix_uy`match =&gt; args.TryGetValue(match.Groups [1] .Value,out var val)吗?val:“ *无论*” (2认同)

All*_*ang 26

用Linq做到这一点:

var newstr = dict.Aggregate(str, (current, value) => 
     current.Replace(value.Key, value.Value));
Run Code Online (Sandbox Code Playgroud)

dict是你的搜索替换对定义的Dictionary对象.

str是你需要做一些替换的字符串.


Jon*_*eet 9

对我来说似乎是合理的,除了一件事:它对订单敏感.例如,输入一个"$ x $ y"的输入字符串和一个替换字典:

"$x" => "$y"
"$y" => "foo"
Run Code Online (Sandbox Code Playgroud)

替换的结果 "foo foo"或"$ y foo",具体取决于首先执行的替换.

您可以使用a List<KeyValuePair<string, string>>来控制排序.另一种方法是遍历字符串,确保在进一步的替换操作中不使用替换.但这可能要困难得多.