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

如何扩展AppleScript字符替换函数,同时替换`与'\''序列为'?

解决方案:扩展AppleScript多字符替换或使用Shell命令

一、修改AppleScript代码支持多目标替换

直接修改原有的replaceChars函数,让它支持传入列表形式的替换目标,循环处理每个替换规则即可:

set strng to "Output`s new form should not be these''chars"
set modifiedString to replaceChars(strng, {"`", "''"}, "'")

on replaceChars(inputText, charsOutList, charsIn)
    set resultText to inputText
    -- 逐个处理每个需要替换的字符/字符串
    repeat with charsOut in charsOutList
        set text item delimiters to charsOut
        set textList to text items of resultText
        set text item delimiters to charsIn
        set resultText to textList as text
        set text item delimiters to ""
    end repeat
    return resultText
end replaceChars

这个版本的函数会依次对列表里的每个目标执行替换,最终同时完成→'和''→'的转换,测试原字符串会得到"Output's new form should not be these'chars",完全符合需求。

二、使用Shell命令实现

如果想用Shell命令完成,可借助sed的多替换功能,注意对反引号`做转义处理:

original_str="Output`s new form should not be these''chars"
modified_str=$(echo "$original_str" | sed -e "s/\`/'/g" -e "s/''/'/g")
echo "$modified_str"

sed的-e参数允许连续执行多条替换规则:

  • 第一条规则"s/\/'/g"把所有替换成'`
  • 第二条规则"s/''/'/g"把所有连续的两个单引号替换成一个单引号

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 13:37:48