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

如何按优先级替换三组分隔符并将字符串拆分为指定结构数组?

自定义分隔符拆分字符串(带优先级)

问题分析

你需要将字符串按句号>逗号>空格的优先级替换分隔符,再把内容块和替换后的分隔符拆分为独立数组元素。普通split函数无法处理这种带优先级的多规则拆分,因为它只能基于单一或简单的分隔符模式,无法同时处理替换和拆分的逻辑。

解决方案

这里提供两种可行的实现思路,以JavaScript为例(其他语言可参照逻辑修改):


方法1:逐字符遍历处理(逻辑清晰易扩展)

通过遍历每个字符,按优先级判断是否为分隔符,分别累积内容或添加替换后的分隔符到数组:

const input = "Once there     was a (so-called) rock. it.,was not! in fact, a big rock.";

// 按优先级定义分隔符替换规则
const delimiterRules = [
  { test: char => /[.!?]/.test(char), replaceWith: '.' },
  { test: char => /[,():;"]/.test(char), replaceWith: ',' },
  { test: char => /[ -_]/.test(char), replaceWith: ' ' }
];

const result = [];
let currentContent = '';

for (const char of input) {
  let matchedRule = delimiterRules.find(rule => rule.test(char));
  
  if (matchedRule) {
    // 先把累积的内容加入数组
    if (currentContent) {
      result.push(currentContent);
      currentContent = '';
    }
    // 添加替换后的分隔符
    result.push(matchedRule.replaceWith);
  } else {
    // 非分隔符字符,累积到内容块
    currentContent += char;
  }
}

// 处理最后剩余的内容块
if (currentContent) result.push(currentContent);

console.log(result);

方法2:正则分组匹配(代码更简洁)

通过正则表达式分组匹配内容块和各类分隔符,再根据匹配结果替换并添加到数组:

const input = "Once there     was a (so-called) rock. it.,was not! in fact, a big rock.";

// 正则分组:[1]内容块 [2]句号类分隔符 [3]逗号类分隔符 [4]空格类分隔符
const splitRegex = /([^.!?,():;" -_]+)|([.!?])|([,():;"])|([ -_])/g;
const result = [];

let match;
while ((match = splitRegex.exec(input)) !== null) {
  if (match[1]) {
    result.push(match[1]);
  } else if (match[2]) {
    result.push('.');
  } else if (match[3]) {
    result.push(',');
  } else if (match[4]) {
    result.push(' ');
  }
}

console.log(result);

输出结果

两种方法都会得到符合要求的数组:

["Once", " ", "there", " ", "was", " ", "a", " ", ",", "so-called", ",", " ", "rock", ".", " ", "it", ".", ",", "was", " ", "not", ".", " ", "in", " ", "fact", ",", " ", "a", " ", "big", " ", "rock", "."]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 04:17:19