.NET集合:如何从现有列表提取起止值间的多段新列表
按起止值提取字符串列表中的连续子列表
给定一个包含多组起止标记的字符串列表,需要提取每组起止标记之间(包含起止标记本身)的连续条目,生成对应类别的独立子列表。以下是具体实现方案:
需求示例
原始列表:
const stringList = [ "16a_Start", "test1", "test11", "16a_End", "15a_start", "test3", "test33", "15a_end", "16a_Start", "test2", "test22", "16a_End", "15a_start", "test4", "test44", "15a_end" ];
期望结果:
16aList包含所有16a_Start到16a_End的连续片段15aList包含所有15a_start到15a_end的连续片段
实现代码(JavaScript)
// 原始字符串列表 const stringList = [ "16a_Start", "test1", "test11", "16a_End", "15a_start", "test3", "test33", "15a_end", "16a_Start", "test2", "test22", "16a_End", "15a_start", "test4", "test44", "15a_end" ]; // 定义提取规则:键为类别标识,值为对应的起止标记 const extractRules = { "16a": { start: "16a_Start", end: "16a_End" }, "15a": { start: "15a_start", end: "15a_end" } }; // 初始化结果容器 const result = { 16aList: [], 15aList: [] }; // 遍历处理逻辑 let currentBatch = null; let activeCategory = null; for (const item of stringList) { // 检查是否触发某个类别的起始标记 for (const category in extractRules) { if (item === extractRules[category].start) { currentBatch = [item]; activeCategory = category; break; } } // 处于收集状态时,持续添加元素 if (currentBatch && activeCategory) { // 避免重复添加起始标记(已在初始化时加入) if (item !== extractRules[activeCategory].start) { currentBatch.push(item); } // 检查是否到达结束标记,完成当前批次收集 if (item === extractRules[activeCategory].end) { result[`${activeCategory}List`].push(currentBatch); currentBatch = null; activeCategory = null; } } } // 输出结果 console.log("16aList:", result.16aList); console.log("15aList:", result.15aList);
关键逻辑说明
- 提取规则配置:通过
extractRules统一管理所有需要提取的类别及其起止标记,后续新增类别只需扩展此对象即可。 - 状态跟踪:用
currentBatch保存当前正在收集的子列表,activeCategory标记当前所属类别,确保只收集对应类别的连续条目。 - 批次收尾:遇到结束标记时,将当前收集的子列表存入对应结果数组,并重置状态,准备下一轮收集。
注意事项
- 大小写敏感:代码默认严格匹配起止标记的大小写,若需要忽略大小写,可将匹配逻辑改为
item.toLowerCase() === extractRules[category].start.toLowerCase()。 - 异常处理:如果存在起始标记无对应结束标记、或结束标记无对应起始标记的情况,可添加额外逻辑(如丢弃不完整片段、记录日志)。
- 嵌套场景:若原始列表存在起止标记嵌套的情况,需改用栈结构跟踪状态,避免收集错误的片段。
内容的提问来源于stack exchange,提问作者Murali Krishna
相关产品推荐
相关产品推荐

