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

如何无需索引计数移除字符串中重复的特定词组

极简去重实现方案

已知仅固定词组is example可能出现重复时,完全不需要手动定位索引、统计词组出现次数,用正则反向引用做一次替换即可实现需求,无重复时不会改动原字符串内容。

核心逻辑

通过正则捕获第一个出现的is example词组,匹配该词组后任意位置出现的同词组重复项,直接将多余的重复内容移除,同时自动清理多余空格,避免替换后出现连续空白。

代码示例

JavaScript 实现

// 基础版本,适配标准单空格分隔的场景
const removeDuplicatePhrase = (str) => str.replace(/(is example)(.*?)\1\s*/, '$1$2');

// 鲁棒性版本,适配词组间存在多空格、制表符的场景
const removeDuplicatePhraseRobust = (str) => str.replace(/(is\s+example)(.*?)\1\s*/, '$1$2');

// 测试
removeDuplicatePhrase("this is example of is example string")
// 输出:"this is example of string"
removeDuplicatePhrase("this is example of string")
// 输出:"this is example of string"(无重复时原内容不变)

Python 实现

import re

def remove_duplicate_phrase(s: str) -> str:
    # 基础版本
    return re.sub(r'(is example)(.*?)\1\s*', r'\1\2', s)

def remove_duplicate_phrase_robust(s: str) -> str:
    # 适配多空白的鲁棒版本
    return re.sub(r'(is\s+example)(.*?)\1\s*', r'\1\2', s)

# 测试
print(remove_duplicate_phrase("this is example of is example string"))
# 输出:this is example of string

方案优势

  • 无需提前遍历字符串、定位词组索引、统计出现次数,一行代码即可完成处理
  • 正常无重复的返回内容不会被改动,不会引入额外异常
  • 自动处理多余空格,替换后的字符串格式符合正常书写规范
  • 若后续出现词组重复2次以上的极端场景,给正则加上全局匹配标识即可一次性清除所有多余重复项

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 14:36:30