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

如何通过Mule流结合DataWeave 2.0在字符串指定索引插入字符

Mule结合DataWeave实现字符串指定索引插入字符方案

需求说明

在输入字符串的指定索引位置插入空格,索引值由payload.indexes数组提供,仅使用Mule流搭配DataWeave完成转换。

Mule流配置

仅需在Mule流中添加1个Transform Message组件即可完成全流程转换,无需引入其他额外组件,组件内直接编写DataWeave脚本处理输入payload即可。

DataWeave转换逻辑(DataWeave 2.0)

%dw 2.0
output application/json
---
{
    string: do {
        // 将索引倒序排列,从后往前插入避免已插入的空格影响后续索引定位
        var sortedIndexes = payload.indexes orderBy -$
        // 将原字符串拆分为字符数组
        var originCharArray = payload.string splitBy ""
        // 遍历索引逐个插入空格
        var processedArr = sortedIndexes reduce((insertIdx, arr = originCharArray) -> 
            arr[0 to insertIdx - 1] + [" "] + arr[insertIdx to -1]
        )
        // 拼接处理后的字符数组为字符串
        ---
        processedArr joinBy ""
    }
}

效果验证

输入示例

{
  "string": "putbackthespaces",
  "indexes": [
    3,
    8,
    12
  ]
}

输出示例

{
  "string": "put back the spaces"
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 10:09:01