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

Python如何按规则实现字符串指定子串的条件替换

问题解决方法

直接用正则匹配+替换回调的方式就能同时覆盖两种替换场景,不会出现普通replace全局替换的误匹配问题。

核心逻辑

先通过正则捕获所有以-tion结尾的独立片段,根据片段内-的数量执行对应替换:

  • 片段内总共有1个-(即[无横杠内容]-tion结构):把末尾的tion替换为cloud,最终得到[原前缀]-cloud
  • 片段内总共有2个-(即[带1个横杠的内容]-tion结构):直接删除末尾的-tion,保留前面的内容即可

Python 实现代码

import re

str1 = "lol-tion haha-futures-tion yo-tion ard-tion pomo-tion"

def match_replace(match_res):
    prefix_content = match_res.group(1)
    if prefix_content.count('-') == 0:
        # 单横杠场景,替换tion为cloud
        return f"{prefix_content}-cloud"
    else:
        # 双横杠场景,去掉-tion
        return prefix_content

result = re.sub(r'(\S+?)-tion\b', match_replace, str1)
print(result)

运行输出:

lol-cloud haha-futures yo-cloud ard-cloud pomo-cloud

和预期结果完全一致。

JavaScript 实现代码

前端/Node.js 环境可以用相同逻辑实现:

const str1 = "lol-tion haha-futures-tion yo-tion ard-tion pomo-tion";
const result = str1.replace(/(\S+?)-tion\b/g, (_, prefix) => {
  const dashNum = (prefix.match(/-/g) || []).length;
  return dashNum === 0 ? `${prefix}-cloud` : prefix;
});
console.log(result);

这种实现方式不会出现替换顺序导致的逻辑错误,后续如果要新增更多横杠数量对应的替换规则,只需要在回调函数里加判断分支即可,维护成本很低。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.02 08:39:29