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

MUMPS中替换含旧字符串的新字符串时结果异常如何解决?

问题分析与解决

你的代码出现问题的核心原因是从前往后替换时,新字符串包含旧字符串,导致后续循环误匹配到刚插入的旧字符串,同时循环次数的计算逻辑也有误。

原代码中,每次替换第一个"old"为"very old"后,字符串变成"My very old old friend",下一次循环会立刻匹配到刚插入的"old",把它替换成"very old",最终得到错误结果。

正确实现方式

方式一:使用内置$REPLACE函数(推荐)

多数MUMPS实现(如InterSystems IRIS)提供了原生字符串替换函数,直接调用即可完成需求:

s str="My old old friend"
s old="old"
s new="very old"
s str=$REPLACE(str,old,new)
q str

方式二:手动从后往前替换

如果环境不支持$REPLACE,可以从字符串末尾开始向前查找替换,避免新插入的内容干扰匹配:

s str="My old old friend"
s old="old"
s new="very old"
n pos, oldLen, newLen
s oldLen=$L(old)
s newLen=$L(new)
; 从字符串末尾开始找第一个匹配的old位置
s pos=$F(str,old,,-1)
while pos>0 {
    ; 替换当前匹配的old为new
    s str=$E(str,1,pos-1)_new_$E(str,pos+oldLen,*)
    ; 向前移动位置,跳过刚替换的区域,继续查找下一个匹配
    s pos=$F(str,old,pos-oldLen-1,-1)
}
q str

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 18:40:35