如何修改代码识别并移除文本中无闭合的引号("、')?
识别并移除未闭合引号实体的TypeScript实现思路
核心逻辑
通过栈结构跟踪引号配对状态,遍历文本识别所有目标引号实体("、'),标记未配对的实体后从原文本中移除。
具体实现步骤
- 定义目标实体映射:先明确要处理的两种引号实体及其类型,方便后续判断配对关系:
const quoteEntityMap = { '"': 'double', ''': 'single' }; - 遍历匹配引号实体:用全局正则
/("|')/g逐个捕获文本中的引号实体,同时维护一个栈记录未闭合的引号:- 若当前实体与栈顶引号类型一致,说明找到配对,弹出栈顶(标记为已闭合)
- 若栈为空或类型不匹配,将当前实体的位置、长度、类型压入栈(标记为待闭合)
- 处理未闭合实体:遍历结束后,栈中剩余的就是无配对的引号实体。为避免拼接时索引偏移,先将这些实体按起始位置倒序排列,再逐个从原文本中截取移除。
- 输出处理后文本:拼接所有未被移除的文本片段,得到结果。
完整代码示例
function removeUnclosedQuotes(text: string): string { const quoteEntityMap = { '"': 'double', ''': 'single' }; const entityRegex = /("|')/g; const stack: { type: string; start: number; length: number }[] = []; // 遍历所有匹配的引号实体,跟踪配对状态 let match: RegExpExecArray | null; while ((match = entityRegex.exec(text)) !== null) { const entity = match[0]; const type = quoteEntityMap[entity as keyof typeof quoteEntityMap]; const start = match.index; const length = entity.length; if (stack.length && stack.at(-1)!.type === type) { stack.pop(); } else { stack.push({ type, start, length }); } } // 倒序移除未闭合的引号实体,避免索引偏移 stack.sort((a, b) => b.start - a.start); let result = text; for (const unclosed of stack) { result = result.slice(0, unclosed.start) + result.slice(unclosed.start + unclosed.length); } return result; } // 测试用例 const sampleText = '"未闭合的双引号示例'还有未闭合的单引号'; console.log(removeUnclosedQuotes(sampleText)); // 输出:未闭合的双引号示例还有未闭合的单引号
内容的提问来源于stack exchange,提问作者Alen.Toma
相关产品推荐
相关产品推荐

