You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#中如何使用列表连续元素单次替换字符串中的相同占位符

解决方案

用正则表达式的匹配回调替换机制就能完美满足需求,只需要单次扫描文本即可完成所有占位符的顺序替换,完全避免多次string.Replace带来的多轮遍历性能损耗,实现逻辑也非常简单。

核心思路

  1. 构造匹配$modifier的正则:注意$是正则特殊字符,需要转义,所以正则模式写为\$modifier
  2. 维护一个指向值列表的索引指针,初始值为0
  3. 每次匹配到占位符时,返回当前索引对应的值,再将索引自增1,自动实现按顺序取值替换

代码示例(C#)

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

public static class ModifierReplacer
{
    // 预编译正则,重复调用时性能更高
    private static readonly Regex _modifierRegex = new Regex(@"\$modifier", RegexOptions.Compiled);

    public static string Replace(string input, List<float> values)
    {
        int valueIndex = 0;
        return _modifierRegex.Replace(input, match =>
        {
            // 取值正常返回对应值,值列表不足时可根据需求返回原占位符或者默认值
            return valueIndex < values.Count ? values[valueIndex++].ToString() : match.Value;
        });
    }
}

调用测试

string originText = "<em>Provides a +$modifier% bonus to Maximum Quality and a +$modifier% chance for Special Traits when developing a Recipe.</em>";
List<float> values = new List<float> { 5, 0.5f };
string result = ModifierReplacer.Replace(originText, values);
// 输出结果完全符合预期:<em>Provides a +5% bonus to Maximum Quality and a +0.5% chance for Special Traits when developing a Recipe.</em>

其他语言通用实现

所有支持正则回调替换的语言都可以复用这套逻辑,核心逻辑完全一致:

  • JavaScript:str.replace(/\$modifier/g, () => values[index++])
  • Python:re.sub(r'\$modifier', lambda _: str(values[index := index+1]), input_str)(Python3.8+支持海象运算符,低版本单独维护索引即可)

性能优势

  • 全程仅对原文本做1次扫描,时间复杂度为O(n)(n为文本长度),和占位符数量无关
  • 避免了多次string.Replace每次遍历全文、生成中间字符串的额外开销,文本越长、占位符越多,性能优势越明显

内容的提问来源于stack exchange,提问作者drHogan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 19:48:03