JavaScript正则匹配数字、数字区间、数字+前缀文本分组 解决空匹配问题
原正则的空匹配问题来源
你当前使用的正则会返回空字符串,核心有三个设计偏差:
- 变长负向后行断言
(?<!\n\d[-+]*)逻辑错位,会在正常的条目起始位置拦截匹配,导致两个条目之间的空隙处生成无效空串 - 前瞻规则没有完整覆盖条目前缀的全部格式,漏了
-、+的匹配场景,会把跨排版的条目内容错误拆分 - 没有锚定条目的行首起始位置,非贪婪匹配会提前终止,导致匹配内容碎片化
正确实现方案
核心正则规则
直接锚定所有条目的统一起始特征编写匹配逻辑,最终可复用的正则为:/^\d[\d+-]* .*?(?=^\d[\d+-]* |$)/gms
规则拆解
- 匹配逻辑部分:
^\d[\d+-]*:精准匹配每个条目的固定开头——从行首开始,第一个字符是数字,后续可接任意数量的数字、横杠、加号,最后紧跟一个空格,完全覆盖单个数字、数字区间、带+号的所有前缀格式.*?:非贪婪匹配,从条目前缀开始延伸内容,尽可能少地匹配字符,直到遇到下一个条目的开头位置(?=^\d[\d+-]* |$):前瞻终止规则,当匹配到下一个条目的开头、或到达整个文本的末尾时,立即停止当前条目匹配
- 修饰符作用:
g:全局遍历匹配,提取文本中所有符合规则的条目m:多行模式,让^可以匹配每一行的开头,适配跨换行排版的条目识别s:点号通配换行,让跨多行排版的条目内容(比如手动换行拆成两行的长文本)不会被提前截断
可运行代码示例
const inputText = `1 Failure, mutation may not be used again that day, roll on defects table. 2-11 Failure, mutation may not be used again that day. 12-13 The mutant releases a single flash of light that blinds one target for 1d3 rounds (save for half the duration), or optionally the mutant may generate a field of ambient light in a 40’ radius for 1 hour/CL. 14-17 The mutant releases a single flash of light that blinds one target for 1d6 rounds, save for half the duration. 18-19 The mutant releases a single flash of light that blinds up to 6 targets for 1d6 rounds, save for half the duration. 20-23 The mutant releases a series of strobing light pulses that blind and stun up to 6 targets for 1d6 rounds. 24-27 The mutant releases a cascade of dazzling light pulses that hypnotize up to 10 HD of targets for 1d8 rounds (save for half the duration) and places them in a highly suggestible state. 28-29 The mutant’s body releases a gigantic orb of pure photons that deals 6d6 damage to any targets in a straight path to its final target, blinding anyone looking for 1d10 rounds (save for half damage and duration). 30-31 The mutant fires a high energy beam of coherent light that permanently blinds one target and causes 8d6 of damage, save for temporary blindness (1d10 turns) and half damage. 32+ The mutant fires a high energy beam of coherent light that permanently blinds one target and causes 10d6 of damage, save for temporary blindness (1d10 days) and half damage; up to four additional adjacent targets are blinded for 1d10 rounds.`; const entryRegex = /^\d[\d+-]* .*?(?=^\d[\d+-]* |$)/gms; // 提取匹配结果,清理多余的换行和连续空白 const entryList = inputText.match(entryRegex)?.map(item => item.replace(/\s+/g, ' ').trim()) ?? [];
该实现运行后,数组的每一个元素都会对应一个独立的条目,不会出现空字符串,跨换行的长文本内容也会被正确归到所属条目下,匹配效果和预期完全一致。
内容的提问来源于stack exchange,提问作者Jack Condon
相关产品推荐
相关产品推荐

