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

如何将字符串中的占位符按顺序替换为字符串数组的值?

最优实现方案

JavaScript 实现

利用正则表达式的全局替换功能,匹配{{数字}}格式的占位符,通过回调函数映射到数组对应索引的值(注意占位符是1起始,数组是0起始,需减1):

const templateStr = 'test {{1}} this {{2}} {{3}}';
const replaceValues = ['now', 'code', 'block'];

const finalStr = templateStr.replace(/{{(\d+)}}/g, (_, num) => {
  const index = parseInt(num) - 1;
  return replaceValues[index] ?? _; // 数组无对应值时保留原占位符
});

console.log(finalStr); // 输出:'test now this code block'

Python 实现

借助re.sub方法结合匿名函数,完成占位符与数组值的映射,同时做索引越界的容错处理:

import re

template_str = 'test {{1}} this {{2}} {{3}}'
replace_values = ['now', 'code', 'block']

final_str = re.sub(r'{{(\d+)}}', lambda match: 
    replace_values[int(match.group(1)) - 1] 
    if int(match.group(1)) - 1 < len(replace_values) 
    else match.group(0), 
    template_str
)

print(final_str) # 输出:'test now this code block'

方案优势

  • 全局正则替换只需一次遍历字符串,执行效率高
  • 支持任意数量的顺序占位符,扩展性强
  • 包含容错逻辑,当数组长度不足时会保留原占位符,避免程序报错

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 20:40:59